我需要测试函数GetPollData(),我已经编写了Apitest类,创建了该类的模拟对象,并创建了一个测试方法TestGetPollData(),它将检查返回值和期望值是否
无论是否相等,我得到的返回值是20,而不是预期的10。我调试并检查了在.But中创建的业务对象
类构造函数没有被模拟,依赖关系返回的是在类中初始化的值,而不是我想要返回的模拟值。有一种方法可以模拟在构造函数中创建的对象,或者让.Is按照我预期的方式工作。我使用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);
}
}发布于 2020-04-16 18:30:02
关于使用Moq可以模拟的内容有一些限制。这里更详细地介绍了这一点。
Can I use moq Mock to mock a class , not an interface?
更常见的是将Moq与一个接口或至少一个抽象类一起使用。
我重构了您的代码,以便API实现接口IAPI。然后模拟IAPI。
我更改了您的测试方法,以便您可以从模拟对象而不是实际对象调用GetPollData()方法。
它还建议将你对Business类的依赖注入到API的构造函数中,这样你可以在以后需要的时候Mock。我会让你这么做。
using Moq;
using NUnit.Framework;
namespace EntitlementServer.Core.Tests
{
public interface IAPI
{
int GetPollData();
}
public class API : IAPI
{
public Business business { get; set; }
public API()
{
business = new Business();
}
public int GetPollData()
{
return 20;
}
}
public class Business
{
public int polltime()
{
return Service.poll;
}
}
public static class Service
{
public static int poll = 20;
}
[TestFixture]
public class Apitest
{
// Testing the GetPollData method
[Test]
public void TestGetPollData()
{
var api = new Mock<IAPI>();
api.Setup(x => x.GetPollData()).Returns(10);
int value = api.Object.GetPollData();
Assert.AreEqual(10, value);
}
}
}发布于 2020-04-16 16:48:53
你必须通过注入依赖来重构它。
public class API {
public Business business { get; set; }
public API( Business b )
{
business= b;
}
public int GetPollData()
{
return business.polltime();
}
}在测试中,将被模拟的Business传入API,并测试被模拟的实例的polltime是否被调用。
https://stackoverflow.com/questions/61245894
复制相似问题