Using Moq to Test Private Methods

I want to test the following logic (this is obviously a stripped-down version of my method):

public void myPublicMethod(params) { if(some_condition) privateMethod1(); else privateMethod2(); } 

I have all the other dependencies in the method, and I set this to ensure that some_condition is true. What I want to do is check that my privateMethod1 () is called exactly once, and privateMethod2 () is not called at all. Is this possible with Moq?

Here are some notes on the problem:

  • privateMethod1 () and privateMethod2 () are within the same class as myPublicMethod, so I cannot create an object layout for this class.
  • The privateMethod1 / 2 bodies contain many, many dependencies on the class that contains these and myPublicMethod, so splitting privateMethod1 / 2 into its own helper class will be prohibitively time consuming.

Any thoughts? Thanks in advance. I agree that this cannot be done, but I would like to know one way or another.

+4
private-members unit-testing moq mocking
source share
2 answers

Do not check personal methods. These are private details of the class implementation. You should check the results of performing public methods. As long as your results come out as expected, you don't care how the result is obtained.

Building tests for private methods will lead to fragile tests that break easily when you reorganize private implementations (for performance or other reasons).

+16
source share

There are two private utility methods in your class that encapsulate some useful behavior, and the public method you are testing should use this behavior. However, when you test, you do not want the normal behavior of these methods, you want to replace the test behavior. What you have here is a classic case of addiction. When testing, dependencies between classes can be problematic.

So, the solution is the same as for the external dependency: use dependency injection of one type or another to uninstall the method you want to test from private methods that implement the behavior. For example, two private delegates can be declared to represent behavior:

 private Action Behavior1; private Action Behavior2; 

In the class constructor, normal behavior is implemented as follows:

 public Foo (...) { Behavior1 = privateMethod1; Behavior2 = privateMethod2; ... } 

In a public method, a delegate is called instead of the actual method:

 public void myPublicMethod(params) { if(some_condition) Behavior1(); else Behavior2(); } 

Thus, the absolute dependence between the methods has been eliminated, so now it can be checked.

So, now, in the test, after creating the instance of the test object, you can override the dependent behavior:

 Foo_Accessor testMe = new Foo_Accessor(); bool wasCalled1 = false testMe.Behavior1 = new Action(() => wasCalled1 = true); ... Assert.IsTrue(wasCalled1); 
+4
source share

All Articles