Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nsubstitute received called with specific object argument

I have a class that looks something like this:

public myArguments
{
    public List<string> argNames {get; set;}
}

In my test I'm doing this:

var expectedArgNames = new List<string>();
expectedArgNames.Add("test");

_mockedClass.CheckArgs(Arg.Any<myArguments>()).Returns(1);

_realClass.CheckArgs();

_mockedClass.Received().CheckArgs(Arg.Is<myArguments>(x => x.argNames.Equals(expectedArgNames));

But the test fails with this error message:

NSubstitute.Exceptions.ReceivedCallsException : Expected to receive a call matching:
    CheckArgs(myArguments)
Actually received no matching calls.
Received 1 non-matching call (non-matching arguments indicated with '*' characters):
    CheckArgs(*myArguments*)

I'm guessing it's because of the .Equals() but I'm not sure how to solve it?

like image 445
SOfanatic Avatar asked Aug 27 '15 14:08

SOfanatic


People also ask

How do you check if command execute (); has been received by a substitute?

In some cases (particularly for void methods) it is useful to check that a specific call has been received by a substitute. This can be checked using the Received() extension method, followed by the call being checked. In this case command did receive a call to Execute() , and so will complete successfully.

What is NSubstitute C#?

NSubstitute is a friendly substitute for . NET mocking libraries. It has a simple, succinct syntax to help developers write clearer tests. NSubstitute is designed for Arrange-Act-Assert (AAA) testing and with Test Driven Development (TDD) in mind. NSubstitute.Analyzers.CSharp.


1 Answers

In your test, you're comparing a myArguments class with List<string>.

You should either compare the myArguments.argNames with the List<string> or implement the IEquatable<List<string>> in myArguments.

Besides, when you are comparing List<T>, you should use the SequenceEqualsinstead of Equals.

The first option would be:

_mockedClass.Received().CheckArgs(
    Arg.Is<myArguments>(x => x.argNames.SequenceEqual(expectedArgNames)));

The second would be:

public class myArguments : IEquatable<List<string>>
{
    public List<string> argNames { get; set; }

    public bool Equals(List<string> other)
    {
        if (object.ReferenceEquals(argNames, other))
            return true;
        if (object.ReferenceEquals(argNames, null) || object.ReferenceEquals(other, null))
            return false;

        return argNames.SequenceEqual(other);
    }
}
like image 169
Marcio Rinaldi Avatar answered Nov 14 '22 23:11

Marcio Rinaldi