6

Unit tests should be isolated, automated ( ie we don't need to do any prior-configuration for all tests to run at the click of a button ) and consistent in their results. For these reasons we should stub any external dependencies ( ie databases, webservices etc ) used by unit under test UUT ( with integration tests UUTs do use external dependencies ).

But based on what criteria do we decide which internal dependencies called by UUT ( by internal dependencies I'm referring to code which is under our control and that doesn't communicate with any external systems ) also need to be stubbed and which don't need to be?

Is perhaps the criteria that methods defined in the same class as UUT don't need to be stubbed, while methods defined in other classes should be, or ...?

  • 1
    Any method that has been tested lately (for some definition of lately) doesn't need to be stubbed. – BobDalgleish Apr 17 '14 at 22:05
10

The criteria of "Is it currently being tested by this specific unit test?"

If it's not being tested, yeah, stub it, mock it, fake it, set it to a hard known value, whatever. That way you know it's impact on the thing that's actually under test. Even though it's internal to your project and you control the source, it's external to the current thing you're testing.

  • 1
    So you're saying that even methods defined in the same class as UUT should be stubbed, regardless of how simple they are and even if they don't have any side-effects? But where do we draw the line?! What I mean is that most code we write usually has dependencies on framework's lower-level libraries ( StringComparer, StringFormatter, Int32 etc) and we usually shouldn't replace these low-level dependencies. So when is dependency low-level enough for us not to replace it with a stub? – bckpwrld Apr 10 '14 at 21:31
  • 1
    How about: You mock/stub/whatnot your dependencies when your tests start testing the ways the dependencies could fail rather than the part you're interested in. The dependencies could have their own test if you're concerned about that. – Philip Apr 10 '14 at 22:04
  • 1
    Hopefully, the lower level dependencies should have their own set of unit tests. Layer the unit tests at each level. When you go up a level, mock out the lower level. – Jay Atkinson Apr 11 '14 at 2:46
  • @Philip: Just to be sure – you are saying that even methods defined in the same class as UUT should be stubbed, regardless of how simple they are and even if they don't have any side-effects? – bckpwrld Apr 11 '14 at 15:02
  • 4
    You're looking for a hard-set blanket rule that applies at all levels. Stop that. Write out the tests to test what you want tested. If you find yourself getting bogged down by the dependencies, fake 'em. – Philip Apr 11 '14 at 17:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.