简体   繁体   中英

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>>>());

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?

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>>>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM