moswald
moswald

Reputation: 11677

Can NSubstitute check calls that take an Expression<T>?

I'm trying to validate a call to a method that takes a parameter of type Expression<Func<T, U>>, but I'm not able to get NSubstitute to recognize it.

public interface IFoo<T>
{
    void DoThing<TProperty>(TProperty i, Expression<Func<T, TProperty>> expression);
}

// this almost works, but throws AmbiguousArgumentException
myFoo.Received(1).DoThing(Arg.Is(10), Arg.Any<Expression<Func<MyClassType, long>>>());

Upvotes: 1

Views: 593

Answers (2)

moswald
moswald

Reputation: 11677

So while trying to figure out why my tests failed but David Tchepak's worked, I realized my original question did not include the fact that the type of the property was generic as well (question has been updated). When I made that change to David's code, I started seeing the same errors as in my original code.

I have found the solution, however:

// fails with AmbiguousArgumentException
myObj.Received(1).DoThing(Arg.Is(10), Arg.Any<Expression<Fun<MyClassType, long>>>());

// passes, but doesn't validate first parameter
myObj.Received(1).DoThing(Arg.Any<long>(), Arg.Any<Expression<Fun<MyClassType, long>>>());

// passes, _and_validates first parameter
myObj.Received(1).DoThing(10, Arg.Any<Expression<Fun<MyClassType, long>>>());

// passes, _and_validates first parameter
myObj.Received(1).DoThing(Arg.Is<long>(10), Arg.Any<Expression<Fun<MyClassType, long>>>());

Upvotes: 0

David Tchepak
David Tchepak

Reputation: 10484

Yes NSubstitute can work with calls that take expressions. The following test passes for me:

public class MyClassType {
    public long Property { get; set; }
}
public interface IFoo {
    void DoThing(int i, Expression<Func<MyClassType, long>> expression);
}

[Test]
public void ReceivedWithAnyExpression() {
    var myObj = Substitute.For<IFoo> ();
    myObj.DoThing (10, x => x.Property);
    myObj.Received(1).DoThing(Arg.Is(10), Arg.Any<Expression<Func<MyClassType, long>>>());
}

What is the compile error you are getting?

Upvotes: 1

Related Questions