Unit test class with stubs. Should I configure stubs to return ALWAYS correct values?

StackOverflow https://stackoverflow.com/questions/8777153

  •  15-04-2021
  •  | 
  •  

Question

this is one of my questions about unit testing.

I'm reading The Art Of Unit Testing and at chapter 3 the author shows how to remove dependency between one or more classes. That seems clear to me. What's not absolutely clear is the following point.

When I configure a test method with a stub, I configure it to return a specific value. Then I call the tested method exposed by the tested class. This method executes some logic and uses the return value of the stub. The problem is: if the stub is configured to return the wrong value my test will probably fail.

So the question is: when I use stubs, should I ALWAYS configure them to return the expected value? In my opininon this should be the correct way to test as if the stub return always the expected value I'm sure to test only the logic inside the tested method.

What do you think about this? Is there some case in which has some kind of sense to oblige the stub to return uncorrect values?

Thanks a lot, Marco

Was it helpful?

Solution

You are testing how the sut (system under test) works under several conditions:

  • the good path = configuring stubs to return good values and test that the sut behaves accordingly
  • the sad path(s) = configure stubs with wrong values and verify that the sut can handle such cases (e.g. you can test that it throws an Exception using the ExpectedException attribute if you're using nUnit)

OTHER TIPS

You could configure the stub method to return value depending on the test setup in some scenarios. In others to return default value, which should be valid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top