Stefano Altieri
Stefano Altieri

Reputation: 4628

Verify which method was called on itself using MOQ?

The object I'm testing will invoke other methods on itself depending on something.

I.e.

class ToTest {
 public void A(MyObject o) {
  if (some_condition)
   this.B(o);
  else 
   this.C(o);
 }
 public void B(MyObject o) { ... }
 public void C(MyObject o) { ... }
}

How can I verify that method B() was invoked?

Upvotes: 4

Views: 172

Answers (2)

StuartLC
StuartLC

Reputation: 107367

If B and C aren't virtual, then you won't be able to directly verify these methods with Moq, as they are tightly coupled to A.

You may however be able to verify the branch indirectly, e.g. if B and C do different things to Object o, then you may be able to detect this, or alternatively if B and C themselves invoke Mockable dependencies, e.g. if B invokes a ILogger and C invokes an ORM Update, then you can verify the branch indirectly through the presence of the indirect interactions.

Otherwise, I would suggest code refactoring, either:

  • Make B and C virtual, so that they can be verified by Moq (possibly with a CallBase=true, if relevant to the test on the SUT)
  • If B and C represent different concerns (in the SOLID sense), then consider other refactorings, such that the methods B and C themselves are relocated to mockable dependencies.

Upvotes: 2

severin
severin

Reputation: 5503

You can't. You can verify if methods have been called on a mock object, but having an object moq itself is impossible.

If MyObject is indeed a mock object you can use:

mockObject.Verify(m => m.B(It.IsAny<Type>()), Times.Exacly(n))

Upvotes: 2

Related Questions