[英]Unit test command class with mock repository
我的應用程序是使用CQRS模式和存儲庫設計的,如何在不連接數據庫的情況下為命令類創建單元測試?
我們正在使用Moq來創建我們的存儲庫的模擬。
您必須模擬數據庫層。 同樣,您也可以使用Mock Repositor層代替Database Layer。
[TestClass]
public class TestCommandServiceTests
{
private readonly TestService _testService;
private readonly ITestRepositor _testRepository;
private readonly Mock<IDatabaseLaye> _mock;
[SetUp]
public void Setup()
{
_mock = new Mock<IDatabaseLayer>();
_testRepository = new TestRepository(_mock);
_testService = new TestService(_testRepository);
}
[Test]
public void TestMethod_ValidRequest_ShouldTestSuccessfully()
{
// Arrange
var request = new TestMethodRequest();
this._mock.Setup(c => c.TestSPMethod(null)).Returns(1000);
// Act
var response = _testService.TestMethod(request);
// Assert
Assert.IsNotNull(response);
Assert.AreEqual(1000, response.Id);
}
}
當然你可以模擬數據庫(你甚至應該,教科書說)。 但是這很快變得非常麻煩,特別是當復雜的數據庫約束發揮作用時。
在實踐中,擁有一個本地測試數據庫(例如,如果可能的話,使用SQLite或MS SQL CE在內存中)並且在整個“持久性堆棧”(在您的情況下:命令,存儲庫和數據庫)中進行測試,可能會更有效率走。 這是“ 單元測試藝術 ”一書中推薦的方法,我發現它在實踐中非常有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.