NSubstitute.Analyzers icon indicating copy to clipboard operation
NSubstitute.Analyzers copied to clipboard

NS2002 falsely triggered when substituting an interface

Open davidkeaveny opened this issue 1 year ago • 5 comments

I have a simple interface and a class that dispatches against it:

public interface IReportRunner
{
  void Execute(int year, int month);
}

public class ClassThatTakesInterfaceDependency
{
  private readonly IReportRunner _runner;

  public ClassThatTakesInterfaceDependency(IReportRunner runner)
  {
    _runner = runner;
  }

  public void DoStuffThatInvokesInterface(DateTime now)
  {
    _runner.Execute(now.Year, now.Month);
  }
}

When I create a test that exercises the interface, I'm getting an NS2002 error when creating the substitute:

The number of arguments passed to NSubstitute.Substitute.For do not match the number of constructor arguments for IReportRunner. Check the constructors for IReportRunner and make sure you have passed the required number of arguments.

public class WhenRunningMyTest
{
  [Fact]
  public void ItShouldExecuteSuccessfully()
  {
    // Arrange
    var substitute = Substitute.For<IReportRunner>();
    var sut = new ClassThatTakesInterfaceDependency(substitute);
    
    // Act
    sut.DoStuffThatInvokesInterface(new DateTime(2023, 6, 5));

    // Assert
    substitute.Received(1).Execute(2023, 6);
  }
}

Given that it is substituting an interface, it shouldn't be complaining about constructor parameters.

I am using NSubstitute 5.0.0 with NSubstitute.Analyzers 1.0.16.

davidkeaveny avatar Jun 06 '23 04:06 davidkeaveny