Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid duplicate code when using mocks in unittests

I am using dependency injection to supply mocks for code outside of my class under test. I find myself writing alot of the same code over and over as I need to mock out AuthProvider, ConfigurationManager, etc. which are used in the method I want to test. The method contains branches (if-then-else) and therefore I have multiple tests in place to test all execution paths of the method. I am instantiating each of the mocks several times (once in each test method) but am wondering if this is the wrong way around? Also I am putting up expectations for the mocks and preset responses which evidently are mostly copy-paste as such calls as to AuthProvider.Authenticate() are called in every method

In each method I setup a mock repository and at the end of each method I verify the mock repository. Should I prehaps have some sort of factory for creating these mocks along with setting their expectations and return values and if so how?

For implementation of mocks I am using RhinoMocks.

like image 201
Fadeproof Avatar asked Jan 06 '09 16:01

Fadeproof


2 Answers

"instantiating each of the mocks several times" is not a problem. Objects are free.

Just be sure you aren't defining the mock classes numerous times. Classes are expensive.

Also, you have a "setUp" method in a TestCase that allows you to create a fixture that is used by all tests. Yes, it's rebuilt for each test. No, that's not a problem unless it's painfully slow.

like image 192
S.Lott Avatar answered Sep 21 '22 14:09

S.Lott


Assuming you're using NUnit, you can use instance variables for your Mocks and reset them in Setup/Teardown. If you see repeated patterns then do what you do with production code: refactor and extract helper methods that express what you're trying to achieve (if there's no commonality at all, then there's a problem with the design of the production code).

If there are significant divisions in setup, consider writing more than one test class for your production class.

Finally, think about whether your production class is just too busy and some of the behaviour ought to be extracted out to a helper object.

Listen to the Tests!

like image 35
Steve Freeman Avatar answered Sep 22 '22 14:09

Steve Freeman