NSubstitute - Check arguments passed to method

JBond picture JBond · Jul 9, 2015 · Viewed 9.3k times · Source

We are currently in the process of moving from RhinoMocks to NSubstitute.

I have a method that takes an object of type DatabaseParams. This class has the following structure (simplified):

public class DatabaseParams
  {
    public string StoredProcName { get; private set; }
    public SqlParameter[] Parameters { get; private set; }

    public DatabaseParams(string storeProcName, SqlParameter[] spParams)
    {
      StoredProcName = storeProcName;
      Parameters = spParams;
    }
  }

I have the following method I want to check the arguments being passed to it are correct:

public interface IHelper
{
Task<object> ExecuteScalarProcedureAsync(DatabaseParams data);
}

How do I test that an instance of DatabaseParams was passed into that method with the correct values?

I could do this in RhinoMocks with something like this:

helperMock.Expect(m => m.ExecuteScalarProcedureAsync(Arg<DatabaseHelperParameters>.Matches(
        p =>   p.StoredProcName == "up_Do_Something"
            && p.Parameters[0].ParameterName == "Param1"
            && p.Parameters[0].Value.ToString() == "Param1Value"
            && p.Parameters[1].ParameterName == "Param2"
            && p.Parameters[1].Value.ToString() == "Param2Value"
        ))).Return(Task.FromResult<DataSet>(null));

The helperMock is mocking the interface IHelper that contains the ExecuteScalarProcedureAsync method.

Answer

JBond picture JBond · Jul 9, 2015

I've figured out the answer myself.

NSubstitute just needs to use the .Received() call and then when you specify your argument to the method. You can specify the argument matching as a predicate.

For example:

  helperMock.Received().ExecuteScalarProcedureAsync(Arg.Is<DatabaseParams>(
   p =>   p.StoredProcName == "up_Do_Something"
        && p.Parameters[0].ParameterName == "Param1"
        && p.Parameters[0].Value.ToString() == "Param1Value"
        && p.Parameters[1].ParameterName == "Param2"
        && p.Parameters[1].Value.ToString() == "Param2Value"));