【发布时间】:2020-04-16 08:32:10
【问题描述】:
我需要测试函数 GetPollData() 并且我已经编写了 Apitest
类并创建了该类的模拟对象并创建了一个测试方法
将检查返回值和预期值的 TestGetPollData() 是
是否相等。但我得到的返回值为 20 而不是预期的
10.我调试并检查了API内部创建的业务对象
类构造函数未被模拟,并且该依赖项返回
在类中初始化的值,而不是我想要的模拟值
返回。有什么方法可以模拟在内部创建的对象
构造函数或使 Apitest 按我的预期工作。我正在使用 nunit
测试框架。
请告诉我我做错了什么以及我应该怎么做?
public class API
{
public Business business { get; set; }
public API()
{
business=new Business();
}
public int GetPollData()
{
return business.polltime();
}
}
public class Business
{
public int polltime()
{
return Service.poll;
}
}
public class Service
{
public int poll=20;
}
//API TEST CLASS
public class Apitest
{
private Mock<API> api = new Mock<API>();
API ApiObj = new ApiObj();
// Testing the GetPollData method
public TestGetPollData()
{
api.Setup( x => x.GetPollData()).Returns(10);
int value=ApiObj.GetPollData();
Assert.AreEqual(10,value);
}
}
【问题讨论】:
-
如果
GetPollData只是返回business.polltime(),为什么不只是测试Business?