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 = "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); }
在控制器級別,我傾向於編寫端到端測試。沒有嘲笑,沒有贗品,只有真實的東西。
原因是在您上面的測試中,您的單元測試與控制器操作的實現細節相耦合。假設您不再使用儲存庫或工作單元,您的測試甚至將不再編譯。在這個級別,您應該關注測試行為,而不是實現。
我對隔離域模型進行單元測試,其餘部分進行集成測試。