我有一个 Controller ,其中有多个依赖项。我为该 Controller 创建了一个参数构造函数,它获取主要依赖项之一(服务层)的对象。
public class ProductController
{
private IProductService _productService ;
public ProductController(IProductService productService)
{
this._productService = productService;
}
}
但是在 Controller 中,有一些方法可以处理多个依赖项。
Public ActionResult GetProductDetails()
{
List<CategoryDto> catList = CategoryService.GetAllCategories()).ToList();
ProductViewModel model = new ProductViewModel
{
Name="",
Categories = catList
};
//other stuffs...
}
block 引用>In the above method there is a different dependency CategoryService.And i want to ask to mock that dependency should i need to make different constructor or can i pass multiple dependency object to same constructor ?
最佳答案
只需将所有依赖项注入(inject)到您正在测试的类 (SUT) 中即可。您可以使用构造函数或属性注入(inject)。我会选择构造函数注入(inject):
public class ProductController
{
private IProductService productService;
private ICategoryService categoryService;
public ProductController(IProductService productService,
ICategoryService categoryService)
{
this.productService = productService;
this.categoryService = categoryService;
}
public ActionResult GetProductDetails()
{
var categories = categoryService.GetAllCategories().ToList();
// ...
}
}
在测试中,您可以使用设置方法(NUnit 语法)创建模拟依赖项并将其传递给 SUT:
private ProductController controller;
private Mock<IProductService> productServiceMock;
private Mock<ICategoryService> categoryServiceMock;
[SetUp]
public void Setup()
{
productServiceMock = new Mock<IProductService>();
categoryServiceMock = new Mock<ICategoryService>();
controller = new ProductController(productServiceMock.Object,
categoryServiceMock.Object);
}
然后,您可以在执行 SUT 之前在测试方法中安排任何此模拟对象:
[Test]
public void ShouldReturnProductDetails()
{
List<CategoryDto> categories = // ...
categoryServiceMock.Setup(cs => cs.GetAllCategories()).Returns(categories);
var result = controller.GetProductDetails();
// Assert
}
关于c# - 在进行单元测试时如何将多个依赖项对象传递给 Controller 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22961910/