Imagine I want to mock the Set method of this interface to return what is being passed on the generic parameter:
public interface IMemoryCache
{
TItem Set<TItem>(object key, TItem value);
}
Using moq I can do it this way:
[Fact]
public void SetupUsingMoq()
{
Mock<IMemoryCache> mock = new();
mock
.Setup(x => x.Set(It.IsAny<object>(), It.IsAny<It.IsAnyType>()))
.Returns((object _, object input) => input);
mock.Object.Set(1, "ok").Should().Be("ok");
}
I've tried doing the same thing using NSubstitute but, unfortunately, this doesn't work:
[Fact]
public void SetupUsingNSubstitute()
{
IMemoryCache mock = Substitute.For<IMemoryCache>();
mock
.Set(Arg.Any<object>(), Arg.Any<Arg.AnyType>())
.Returns(callInfo => callInfo.ArgAt<object>(1));
mock.Set(1, "ok").Should().Be("ok");
}
If you only want to set it up for
strings, you can make the test pass by explicitly configuring the object for that type: