gpt4 book ai didi

c# - 如何处理设置复杂的单元测试并让他们只测试单元

转载 作者:太空狗 更新时间:2023-10-29 23:48:31 25 4
gpt4 key购买 nike

我有一个方法需要 5 个参数。此方法用于获取一堆收集的信息并将其发送到我的服务器。

我正在为此方法编写单元测试,但遇到了一些障碍。一些参数是类的列表<>,需要一些操作才能正确设置。我有在其他单元(生产代码单元)中正确设置它们的方法。但是,如果我调用它们,那么我有点打破了单元测试的整个想法(只命中一个“单元”)。

那么....我该怎么办?我是在我的测试项目中复制设置这些对象的代码(在辅助方法中)还是开始调用生产代码来设置这些对象?

这里是一个假设的例子,试图让这个更清楚:

文件:UserDemographics.cs

class UserDemographics
{
// A bunch of user demographic here
// and values that get set as a user gets added to a group.
}

文件:用户组.cs

class UserGroups
{
// A bunch of variables that change based on
// the demographics of the users put into them.
public AddUserDemographicsToGroup(UserDemographcis userDemographics)
{}
}

文件:UserSetupEvent.cs

class UserSetupEvent
{
// An event to record the registering of a user
// Is highly dependant on UserDemographics and semi dependant on UserGroups
public SetupUserEvent(List<UserDemographics> userDemographics,
List<UserGroup> userGroups)
{}
}

文件:Communications.cs

class Communications
{
public SendUserInfoToServer(SendingEvent sendingEvent,
List<UserDemographics> userDemographics,
List<UserGroup> userGroups,
List<UserSetupEvent> userSetupEvents)
{}
}

所以问题是:要对 SendUserInfoToServer 进行单元测试,我应该在我的测试项目中复制 SetupUserEventAddUserDemographicsToGroup,还是应该调用它们帮我设置一些“真实”参数?

最佳答案

您需要测试副本

单元测试不应调用其他方法是正确的,因此您需要“伪造”依赖项。这可以通过以下两种方式之一完成:

  1. 手写测试副本
  2. mock

测试副本允许您将被测方法与其依赖项隔离开来。

我使用 Moq mock 。您的单元测试应发送“虚拟”参数值,或可用于测试控制流的静态定义值:

public class MyTestObject
{
public List<Thingie> GetTestThingies()
{
yield return new Thingie() {id = 1};
yield return new Thingie() {id = 2};
yield return new Thingie() {id = 3};
}
}

如果该方法调用任何其他类/方法,请使用模拟(又名“假货”)。模拟是基于虚拟方法或接口(interface)动态生成的对象:

Mock<IRepository> repMock = new Mock<IRepository>();
MyPage obj = new MyPage() //let's pretend this is ASP.NET
obj.IRepository = repMock.Object;
repMock.Setup(r => r.FindById(1)).Returns(MyTestObject.GetThingies().First());
var thingie = MyPage.GetThingie(1);

上面的 Mock 对象使用 Setup 方法为 r => r.FindById(1) lambda 中定义的调用返回相同的结果。这称为期望。这允许您测试方法中的代码,而无需实际调用任何依赖类。

以这种方式设置测试后,您可以使用 Moq 的功能来确认一切都按照预期的方式发生:

//did we get the instance we expected?
Assert.AreEqual(thingie.Id, MyTestObject.GetThingies().First().Id);
//was a method called?
repMock.Verify(r => r.FindById(1));

Verify 方法允许您测试是否调用了方法。这些工具共同使您可以一次将单元测试集中在一个方法上。

关于c# - 如何处理设置复杂的单元测试并让他们只测试单元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3630742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com