Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it acceptable to use a 'real' utility class instead of mocking in TDD?

I have a project I am trying to learn unit testing and TDD practices with. I'm finding that I'm getting to quite confusing cases where I am spending a long time setting up mocks for a utility class that's used practically everywhere.

From what I've read about unit testing, if I am testing MyClass, I should be mocking any other functionality (such as provided by UtilityClass). Is it acceptable (assuming that UtilityClass itself has a comprehensive set of tests) to just use the UtilityClass rather than setting up mocks for all the different test cases?

Edit: One of the things I am making a lot of setup for. I am modelling a map, with different objects in different locations. One of the common methods on my utility class is GetDistanceBetween. I am testing methods that have effects on things depending on their individual properties, so for example a test that selects all objects within 5 units of a point and an age over 3 will need several tests (gets old objects in range, ignores old objects out of range, ignores young objects in range, works correctly with multiples of each case) and all of those tests need setup of the 'GetDistanceBetween' method. Multiply that out by every method that uses GetDistanceBetween (almost every one) and the different results that the method should return in different circumstances, and it gets to be a lot of setup.

I can see see as I develop this further, there may be more utility class calls, large numbers of objects and a lot of setup on those mock utility classes.

like image 467
pete the pagan-gerbil Avatar asked Nov 05 '10 13:11

pete the pagan-gerbil


1 Answers

The rule is not "mock everything" but "make tests simple". Mocking should be used if

  1. You can't create an instance with reasonable effort (read: you need a single method call but to create the instance, you need a working database, a DB connection, and five other classes).
  2. Creation of the additional classes is expensive.
  3. The additional classes return unstable values (like the current time or primary keys from a database)
like image 191
Aaron Digulla Avatar answered Sep 29 '22 11:09

Aaron Digulla