Alex Rivera | Logout

Mocks or real classes?

Asked 2008-10-07T21:04:49.753
14

Classes that use other classes (as members, or as arguments to methods) need instances that behave properly for unit test. If you have these classes available and they introduce no additional dependencies, isn't it better to use the real thing instead of a mock?

Edit
Report

3 Answers

2

If your 'real things' are simply value objects like JavaBeans then thats fine.

For anything more complex I would worry as mocks generated from mocking frameworks can be given precise expectations about how they will be used e.g. the number of methods called, the precise sequence and the parameters expected each time. Your real objects cannot do this for you so you risk losing depth in your tests.

answered 2008-10-07T21:35:58.193
1

If you don't care for verifying expectations on how your UnitUnderTest should interact with the Thing, and interactions with the RealThing have no other side-effects (or you can mock these away) then it is in my opinion perfectly fine to just let your UnitUnderTest use the RealThing.

That the test then covers more of your code base is a bonus.

I generally find it is easy to tell when I should use a ThingMock instead of a RealThing:

  • When I want to verify expectations in the interaction with the Thing.
  • When using the RealThing would bring unwanted side-effects.
  • Or when the RealThing is simply too hard/troublesome to use in a test setting.
answered 2008-10-07T22:12:06.937
0

If you write your code in terms of interfaces, then unit testing becomes a joy because you can simply inject a fake version of any class into the class you are testing.

For example, if your database server is down for whatever reason, you can still conduct unit testing by writing a fake data access class that contains some cooked data stored in memory in a hash map or something.

answered 2008-10-07T21:40:51.647

Your Answer