NSubstitute 无法确定项目 "Run All Tests" 时要使用的参数规范

NSubstitute cannot determine argument specifications to use when "Run All Tests" of project

我有一个测试方法:

public class MyTests
{
  [Fact]
  public void Test_Method()
  {
     // Arrange 
     var returns = Result.Ok(new List<string>() { "Test" }.AsEnumerable());  

     this.mockService.ServiceMethod(Arg.Any<Guid>()).Returns(returns); //returns Result<IEnumerable<string>>


     //Act
     var actResult = this.anotherService.Backup();

     //Assert
     Assert.True(actResult.Success);
  }
  ...

测试此方法:

public class AnotherService
{

  internal Result Backup()
  {
    var ret = this.mockService.ServiceMethod().Value;

    ...

    return Result.Ok();
  }

当我 运行 该方法仅适用于 Test_Method() 时一切正常。当我尝试 运行 整个 MyTests class 时,我在这个参考方法上收到以下错误:

NSubstitute.Exceptions.AmbiguousArgumentsException: 'Cannot determine argument specifications to use. Please use specifications for all arguments of the same type.'

我相信这个问题与这个场景无关: How NOT to use argument matchers

NSubstitute.Analyzers:

有什么事吗?

评论和问题更新后更新:

如果根据我的原始答案进行更改后仍然存在问题,则可能是夹具中的另一个测试导致了问题。我建议将 NSubstitute.Analyzers 添加到项目中,这样可以在编译时使用 Roslyn 发现 NSubstitute 使用的潜在问题。 (我建议将它添加到所有使用 NSubstitute 的项目中;它确实可以帮助避免很多潜在的问题!)

如果 NSubstitute.Analyzers 没有找到错误,那么很遗憾,我们只剩下 中描述的一些手动步骤。


原回答:

参数匹配器需要与指定调用或断言接收到调用结合使用。

您发布的测试有两个地方可能导致此问题:

  • 正如@Fabio 在评论中提到的,在 mockService.ServiceMethod() 中使用了一个参数匹配器,但没有对应的 .Returns.
  • 参数匹配器用于对 anotherService.Backup()
  • 的实际调用

尝试像这样修改测试:

  [Fact]
  public void Test_Method()
  {
     // Arrange       
     this.mockService.ServiceMethod(Arg.Any<Guid>()).Returns(...);
     //                               ^- Arg matcher   ^- so need Returns()

     //Act
     var actResult = this.anotherService.Backup(Guid.NewGuid());
     //         Do not use arg matchers for real calls -^

     //Assert
     Assert.True(actResult.Success);
  }

在您的夹具中可能还有其他原因导致此问题,但这两种参数匹配器的使用绝对没有帮助!

这些问题在 argument matcher documentation you mentioned; if the documentation is unclear on these points please raise an issue 中进行了描述,并提供了改进此部分的任何建议。从其他角度获取有关文档的意见非常有用,因此我们将不胜感激您在这方面做出的任何贡献!