Search code examples
c#unit-testing.net-corexunitnsubstitute

NSubstitute set up arg with parameter constructor


How do we set up arguments with constructor parameters?

Below is an example use case.

public interface ICalculator
{
    int Add(AddWithValues withValues);
}

public class AddWithValues {
    AddWithValues(int a, int b) {
      A = a;
      B = b;
    }
   
    public int A {get;}
    public int B {get;}
}

calculator = Substitute.For<ICalculator>();
calculator
   .Add(Arg.Is<AddWithValues>(??));

If Add is accepting a and b integers, documentation shows how to set them up. I cant use predicate as A and B are readonly properties. How do we do set up AddWithValues(in turn specific a and b values) in this case?


Solution

  • If I understand your question correctly, we can use the predicate to do this:

    calculator
       .Add(Arg.Is<AddWithValues>(x => x.A == 42 && x.B > 10));
    

    If you define equality on AddWithValues, you could also use that to match the required value:

    calculator
       .Add(new AddWithValues>(42, 21)); // Assuming AddWithValues defines value equality