无法验证通过Xunit模拟调用的方法
使用MOQ 4.18.1测试我的C#代码,我想验证一种方法调用另一种方法。在接受测试的课程中,我有一个:
public class IntegratedPlatformRepository : PvRepository<OutputDTO>, IIntegratedPlatformRepository
{
protected virtual async Task IpSpecificGetterExtras(OutputDTO dto, CancellationToken cancellationToken) { }
public async Task<OutputDTO> GetAsync(Guid uid, CancellationToken cancellationToken = default) {
var dto = ...
await IpSpecificGetterExtras(dto, cancellationToken);
...
}
我想确保ipspecificgetTerextras
在调用getAsync
时被调用,所以我尝试了以下操作:
[Fact]
public async Task GetAsync_Calls_IpSpecificGetterExtras()
{
// Arrange
var mock = new Mock<IntegratedPlatformRepository> {
CallBase = true
};
// Act
await _repo.GetAsync(Guid.NewGuid().ToString());
// Assert
mock
.Protected()
.Verify<Task>(
"IpSpecificGetterExtras", Times.Once(),
ItExpr.IsAny<OutputDTO>(), ItExpr.IsAny<CancellationToken>()
);
}
如果我简单地运行测试,则会失败,说明它会失败。没有执行调用。如果我调试测试并在ipspecificgetterextras
中设置一个断点,则点击点已命中,我可以逐步介绍该方法,因此肯定会被调用。
Using Moq 4.18.1 to test my C# code, I'm wanting to verify a method calls another method. In the class being tested I have this:
public class IntegratedPlatformRepository : PvRepository<OutputDTO>, IIntegratedPlatformRepository
{
protected virtual async Task IpSpecificGetterExtras(OutputDTO dto, CancellationToken cancellationToken) { }
public async Task<OutputDTO> GetAsync(Guid uid, CancellationToken cancellationToken = default) {
var dto = ...
await IpSpecificGetterExtras(dto, cancellationToken);
...
}
I want to ensure that IpSpecificGetterExtras
is called when GetAsync
is called, so I tried this:
[Fact]
public async Task GetAsync_Calls_IpSpecificGetterExtras()
{
// Arrange
var mock = new Mock<IntegratedPlatformRepository> {
CallBase = true
};
// Act
await _repo.GetAsync(Guid.NewGuid().ToString());
// Assert
mock
.Protected()
.Verify<Task>(
"IpSpecificGetterExtras", Times.Once(),
ItExpr.IsAny<OutputDTO>(), ItExpr.IsAny<CancellationToken>()
);
}
If I simply run the test it fails saying the invocation wasn't performed. If I debug the test and set a breakpoint in IpSpecificGetterExtras
the breakpoint is hit and I can step through the method, so it's definitely being called.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基于显示的示例
模拟
未调用。需要对测试进行重构以使其流动完成,以便可以按预期进行验证。
Based on the shown example
mock
was not invoked.The test needs to be refactored to allow it to flow to completion so that it can be verified as expected.