gpt4 book ai didi

asp.net-mvc - 我应该为 Controller 或服务层还是两者都编写单元测试?

转载 作者:行者123 更新时间:2023-12-05 00:23:11 24 4
gpt4 key购买 nike

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

Controller 测试:

  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 = "US" },
new Country() { Id = 2, Name = "India" },
new Country() { Id = 3, 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);
}

最佳答案

在 Controller 级别,我倾向于编写端到端测试。没有 mock ,没有假货,只有真实的东西。

原因是在上面的测试中,您的单元测试与 Controller 操作的实现细节耦合。假设您不再使用存储库或工作单元,您的测试甚至将不再编译。在这个级别,您应该关注测试行为,而不是实现。

我对隔离的域模型进行单元测试,其余部分进行集成测试。

关于asp.net-mvc - 我应该为 Controller 或服务层还是两者都编写单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28614641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com