asp.net-mvc – 我应该为控制器或服务层或两者编写单元测试吗?

我正在学习并尝试使用单元测试来完成我的项目.但是当我尝试使用单元测试编写演示时,我看到控制器的单元测试与服务层相同.下面是我为控制器和服务层编写的单元测试代码

控制器测试:

private Mock<ICountryService> _countryServiceMock;
  CountryController objController;
  List<Country> listCountry;

  [Testinitialize]
  public void Initialize()
  {

      _countryServiceMock = new Mock<ICountryService>();
      objController = new CountryController(_countryServiceMock.Object);
      listCountry = new List<Country>() {
       new Country() { Id = 1,Name = "US" },new Country() { Id = 2,Name = "India" },new Country() { Id = 3,Name = "Russia" }
      };
  }

  [TestMethod]
  public void Country_Get_All()
  {
      //Arrange
      _countryServiceMock.Setup(x => x.GetAll()).Returns(listCountry);

      //Act
      var result = ((objController.Index() as ViewResult).Model) as List<Country>;

      //Assert
      Assert.AreEqual(result.Count,3);
      Assert.AreEqual("US",result[0].Name);
      Assert.AreEqual("India",result[1].Name);
      Assert.AreEqual("Russia",result[2].Name);

  }

服务测试:

private Mock<ICountryRepository> _mockRepository;
  private ICountryService _service;
  Mock<IUnitOfWork> _mockUnitWork;
  List<Country> listCountry;

  [Testinitialize]
  public void Initialize()
  {
      _mockRepository = new Mock<ICountryRepository>();
      _mockUnitWork = new Mock<IUnitOfWork>();
      _service = new CountryService(_mockUnitWork.Object,_mockRepository.Object);
      listCountry = new List<Country>() {
       new Country() { Id = 1,Name = "Russia" }
      };
  }

  [TestMethod]
  public void Country_Get_All()
  {
      //Arrange
      _mockRepository.Setup(x => x.GetAll()).Returns(listCountry);

      //Act
      List<Country> results = _service.GetAll() as List<Country>;

      //Assert
      Assert.IsNotNull(results);
      Assert.AreEqual(3,results.Count);
  }

解决方法

在控制器级别,我倾向于编写端到端测试.没有嘲笑,没有假货,只有真实的东西.

原因是在上面的测试中,您的单元测试与控制器操作的实现细节相关联.假设您不再使用存储库或工作单元,您的测试将不再编译.在这个级别,您应该关注测试行为,而不是实现.

我单元测试隔离域模型,其余的集成测试.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....