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);
Mark bostrom
source share