c# - 在进行单元测试时如何将多个依赖项对象传递给 Controller ​​构造函数?

标签 c# unit-testing dependency-injection moq

我有一个 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...

   }

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/

相关文章:

xcode - OCUnit 测试失败,但 Xcode Log Navigator 显示没有问题

spring - 在 spring-data-jpa 中对存储库方法实现自定义行为

java - 如何在 JAXB 解码对象中使用依赖注入(inject)?

.NET Core 2.0 Autofac 注册类 InstancePerRequest 不起作用

c# - XNA C# 如何让我的模型闪烁?

c# - 是否有任何方法可以截断字符串的一部分,直到在 C# 中遇到第一个数字?

java - JUnit - 指定测试对其他测试的依赖(不跳过任何一个)?

java - Android Studio Robolectric 单元测试 - 默认值无效

c# - 如何使用变量在 C# 中将 MailAddress 定义为 Address?

c# - 使用参数化构造函数创建类的对象 C#