Category Archives: NSubstitute

NSubstitute – Capturing Arguments Passed To A Function

Consider the situation where you are writing a unit test and need to find out what the value of an argument was that was passed to a function. This can be achieved using NSubstitute.

public interface MyInterface
{
    void MyFunction(int parameterOne);
}

public class MyClass : MyInterface
{
    public void MyFunction(int parameterOne)
    {
    }
}

public class Foo
{
    private MyInterface _myClass;

    public Foo(MyInterface myClass)
    {
        _myClass = myClass;
    }

    public void DoWork()
    {
        _myClass.MyFunction(20);
    }
}

Looking at the code above, we are passing the value 20 into MyFunction but we want to unit test that 20 is the value that actually gets passed in. So how do we do that?

[Test]
public void TestThat20IsPassedToMyFunction()
{
    MyInterface myClass = Substitute.For<MyInterface>();

    Foo foo = new Foo(myClass);

    int result = 0;

    myClass.MyFunction(Arg.Do<int>(arg => result = arg));

    foo.DoWork();

    Assert.AreEqual(20, result);
}

Firstly we mock an instance of MyInterface using NSubstitute so that we can determine when functions are called on it. Then we use the Arg.Do statement to capture the passed in arguments to MyFunction and store them in the result variable. Finally its just a simple matter of calling the function we want to test and asserting that the value in result is 20.