admin管理员组

文章数量:1125556

I have a get-only indexer defined on an interface

public interface ISomeInterface
{
  string this[string key] { get; }
}

In a Unit Test with Moq it is valid for any string parameter as the indexer key:

Mock<ISomeInterface> mock = new();
mock
  .Setup(m => m[It.IsAny<string>()]) // <-- valid
  .Returns("anything for all string key");

Unfortunately in NSubstitute the similar seems not possible:

ISomeInterface mock = Subtitute.For<ISomeInterface>();
mock[Arg.Any<string>()] // <-- invalid
  .Returns("anything for all string key");

I know that it is possible to setup the mock indexer for a specific key like in this thread:
How to mock object's indexer with private setter in NSubstitute?

How could I setup the mock indexer Return value for Any key input parameter in NSubtitute?

I have a get-only indexer defined on an interface

public interface ISomeInterface
{
  string this[string key] { get; }
}

In a Unit Test with Moq it is valid for any string parameter as the indexer key:

Mock<ISomeInterface> mock = new();
mock
  .Setup(m => m[It.IsAny<string>()]) // <-- valid
  .Returns("anything for all string key");

Unfortunately in NSubstitute the similar seems not possible:

ISomeInterface mock = Subtitute.For<ISomeInterface>();
mock[Arg.Any<string>()] // <-- invalid
  .Returns("anything for all string key");

I know that it is possible to setup the mock indexer for a specific key like in this thread:
How to mock object's indexer with private setter in NSubstitute?

How could I setup the mock indexer Return value for Any key input parameter in NSubtitute?

Share Improve this question edited 2 days ago SomeBody 8,7332 gold badges18 silver badges36 bronze badges asked 2 days ago TomcatTomcat 485 bronze badges 6
  • Can you add the exact error message you are presented with? – Fildor Commented 2 days ago
  • 1 What version of NSubstitute and .NET are you using? It works just fine for me. – Guru Stron Commented 2 days ago
  • @Fildor: "ISomeInterface does not contin definition for 'Returns'" – Tomcat Commented 2 days ago
  • 1 "ISomeInterface does not contin definition for 'Returns'"- looks like you have a typo or different code. – Guru Stron Commented 2 days ago
  • 1 Note that you have typo Subtitute -> Substitute – Guru Stron Commented 2 days ago
 |  Show 1 more comment

1 Answer 1

Reset to default 2

Using mock[Arg.Any<string>()] works as expected:

[Test]
public void IndexerSubTest()
{
    ISomeInterface mock = Substitute.For<ISomeInterface>();
    mock[Arg.Any<string>()]
        .Returns("anything for all string key");
    Assert.That(mock["qq"], Is.EqualTo("anything for all string key"));
}

Demo @dotnetfiddle.net

本文标签: