我的应用程序是使用 CQRS 模式和存储库设计的,如何在不连接到数据库的情况下为我的命令类创建单元测试?
我们正在使用 Moq 来创建我们存储库的模拟。
最佳答案
你必须模拟你的数据库层。同样,您也可以模拟存储库层而不是数据库层。
[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);
}
}
关于c# - 使用模拟存储库进行单元测试命令类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20725373/