Solving mocking dilemma with Typemock Isolator

Davy Brison writes about mocking dilemma
Basically the question he deals with is how to test this code:

8 public abstract class MyAbstractClass

9 {

10 public void DoSomethingInteresting()

11 {

12 // some stuff would go here…

13 DoSomethingSpecific();

14 // more stuff would go here…

15 }

16

17 protected abstract void DoSomethingSpecific();

18 }

The problem here is that we want to mock DoSomethingSpecific but using other mock frameworks we can’t mock protected and private methods.

Davy writes:
“If I want to use a mocking framework for this, I have two options (that I can think of right now): I either make the abstract method public so the above code would compile, or I can make it protected internal and then allow my internal members to be visible to my Test project. I dislike both approaches”

With Typemock Isolator we can keep our design and mock DoSomethingSpecific using reflective
mocks. Reflective mocks allows you to mock private and protected methods.
Here is how to solve the issue with Typemock Isolator:

19 [Test]

20 public void CallsProtectedAbstractMethod()

21 {

22 MockObject mockObject = MockManager.MockObject<MyAbstractClass>();

23 mockObject.ExpectCall(“DoSomethingSpecific”);

24 mockObject.Strict = false;

25

26 var myObject = mockObject.Object as MyAbstractClass;

27 myObject.DoSomethingInteresting();

28

29 MockManager.Verify();

30 }

The down side is that we are forced to use string to mock the method.
Personally I prefer to pay this price than changing the method visibility.
What do you think?

  • Davy Brion

    http://davybrion.com/blog/2008/07/mocking-dilemma-solved/

    that post covers another very clean solution :)

  • Travis Illig

    The “clean solution” isn’t so great if you already have a base test class you inherit from… and it somehow feels sort of dirty to derive a test fixture from the class you’re supposedly testing. Like a bad code smell. I think I’d choose the Isolator route, or create a derived version of the abstract class where the protected abstract method calls a public method that you have control over in your test.

  • Davy Brion

    actually, the inner class (which is your test fixture) can indeed inherit from another base test class

    i like it a lot more than referring to a method with a string value ;)

  • Travis Illig

    Oh, hang on, I mis-read the solution code.

    Hmmm. I see the draw, but still sort of feel like having to wrap it is a bad code smell. Not that I like the string solution, but I still think I’d do strings over test fixture wrappers.

  • Mo

    Please click the following link to find more information on mocking protected method in our Forum.

TOP