public List<CustomerViewModel> GetResellerCustomersWithProperties(string shortCode)
{
var businessManager = DependencyContainer.GetInstance<ICortexBusinessManager>();
return businessManager.GetResellerCustomersWithProperties(shortCode);
}
我们如何使用具有接口依赖性的Nunit编写测试用例。
答案 0 :(得分:1)
依赖注入是你的朋友。
注意您将需要一个IOC容器,例如Autofac,Unity,StructureMap等......与您的应用程序连接。
在类的构造函数中注入依赖项:
public class CustomerService
{
private ICortexBusinessManager _cortexBusinessManager;
public CustomerService (ICortexBusinessManager cortexBusinessManager)
{
_cortexBusinessManager = cortexBusinessManager;
}
public List<CustomerViewModel> GetResellerCustomersWithProperties(string shortCode)
{
return _cortexBusinessManager.GetResellerCustomersWithProperties(shortCode);
}
}
然后,您可以在单元测试中使用模拟框架来模拟对您的界面的调用。
以下示例使用Moq
public class CustomerServiceTest
{
[Test]
public void GetResellerCustomersWithProperties_ReturnsFromCortextBusinessManager()
{
//arrange
var mockCortexBusinessManager = new Mock<ICortexBusinessManager>();
//if GetResellerCustomersWithProperties is called with s123, return a new list of CustomerViewModel
//with one item in, with id of 1
mockCortexBusinessManager.Setup(m=> m.GetResellerCustomersWithProperties("s123"))
.Returns(new List<CustomerViewModel>(){new CustomerViewModel{Id = 1}});
var customerService = new CustomerService(mockCortexBusinessManager.Object);
//act
var result = customerService.GetResellerCustomersWithProperties("s123");
//assert
Assert.AreEqual(1, result.Count())
Assert.AreEqual(1, result.FirstOrDefault().Id)
}
}