-2 c# asp.net-mvc-4
public List<CustomerViewModel> GetResellerCustomersWithProperties(string shortCode)
{
var businessManager = DependencyContainer.GetInstance<ICortexBusinessManager>();
return businessManager.GetResellerCustomersWithProperties(shortCode);
}
Run Code Online (Sandbox Code Playgroud)
我们如何使用依赖于接口的 Nunit 编写测试用例。
依赖注入在这里是你的朋友。
注意您将需要一个 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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在单元测试中使用模拟框架来模拟对接口的调用。
下面的示例使用最小起订量
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)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9334 次 |
| 最近记录: |