TheWolf
TheWolf

Reputation: 1695

Moq Verify Chaining

If I have a dependency IObjectA which contains PropertyA of type IObjectB having a public method Foo() in IObjectB.

In order to Verify() Foo() was called can either of these be done, which is correct?

Mock<IObjectA> objectA = new Mock<IObjectA>();
Mock<IObjectB> objectB = new Mock<IObjectB>();

//A
objectA.Verify(x => x.PropertyA.Foo());

//B
objectA.Verify(x => x.PropertyA);
objectB.Verify(x => x.Foo());

"B" seems more correct but does not verify and contradicts my debugging "step through", "A" however gets the correct results. Can objectA be interrogated for its properties and those properties used for invocation even though it is a mocked type?

Upvotes: 4

Views: 621

Answers (1)

Joshua Enfield
Joshua Enfield

Reputation: 18288

Why do you think B seems more correct?

Example A is saying inside object A check that PropertyA had foo called on it.

objectA and objectB are not tied in anyway together in this example. So example B seems misleading in its current form, since it is trying to indicate there is some sort of relation.

Now if you use setup to assign objectB to objectA then both examples should work (because you are telling Moq how objectA relates to objectB). Doing this setup creates the relationship you are looking to verify.

Something along the lines of:

objectA.Setup(x => x.PropertyA).Returns(objectB)

This basically says "when PropertyA is called give me back objectB."

Upvotes: 4

Related Questions