[英]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.