Question

I create a mock object with one method

IMyIterface dosGuard = Mock.Of<IMyIterface >(
                dg =>
                dg.IsMethod1(It.IsAny<IPAddress>(), It.IsAny<string>(), It.IsAny<string>()) == false
        );

I would like to specify the predicate for other method also :

dg.IsMethod2(It.IsAny<IPAddress>(), It.IsAny<string>(), It.IsAny<string>()) == false

How can I do it for both methods together?

Was it helpful?

Solution 2

If you want to setup multiple things on your mock object you can't* use the Mock.Of<T> factory method, you need to setup the mock object yourself:

var dosGuardMock = new Mock<IMyInterface>();
dosGuardMock.Setup(dg => dg.IsMethod1(It.IsAny<IPAddress>(), It.IsAny<string>(), It.IsAny<string>())).Returns(false);
dosGuardMock.Setup(dg => dg.IsMethod2(It.IsAny<IPAddress>(), It.IsAny<string>(), It.IsAny<string>())).Returns(false);
var dosGuard = dosGuardMock.Object;

*Alternatively, you can use the factory method, and use the static Mock.Get method to modify the instance created by the factory method:

var dosGuard = new Mock.Of<IMyInterface>();
Mock.Get(dosGuard).Setup(dg => dg.IsMethod1(It.IsAny<IPAddress>(), It.IsAny<string>(), It.IsAny<string>())).Returns(false);
Mock.Get(dosGuard).Setup(dg => dg.IsMethod2(It.IsAny<IPAddress>(), It.IsAny<string>(), It.IsAny<string>())).Returns(false);

However, I prefer the first example, because it draws an explicit difference between the Mock<T> instance and the "mock" T instance.

OTHER TIPS

Yes, you actually can factory build the entire object's structure with Mock.Of<T>() -- it just appears a little quirky at first:

interface IInterface 
{
    int IntMethod();
    string StringMethod();
}
var instance = Mock.Of<IInterface>(ifc => 
                 ifc.IntMethod() == 1 &&
                 ifc.StringMethod() == "Hello");

It uses boolean as MemberAssignment, but aside from that, it would read get me a Mock of IInterface, with an IntMethod returning 1 and a StringMethod returning "Hello". Also the It.IsAny<TType>() for parameters works in the predicate, as well as nested Mock.Of<T> calls.

Once you get going though, it becomes much cleaner, and one can spin up static methods for assignment/updating root test scenarios : i.e. take 'optimal' model and tweak a few fields, without having to re-type the entire model.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top