public List<CustomerViewModel> GetResellerCustomersWithProperties(string shortCode)
{
var businessManager = DependencyContainer.GetInstance<ICortexBusinessManager>();
return businessManager.GetResellerCustomersWithProperties(shortCode);
}
我们如何使用具有依赖性的Nunit编写测试用例。
依赖注入是您的朋友。
请注意,您需要一个IOC容器,例如AUTOFAC,UNITY,结构图等...与您的应用程序有线。
将您的依赖项注入类的构造函数:
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)
}
}