Hi, I found this example in the book JUnit In Action (2nd ed). The first 3 code snippets are from the book. Note: none of these extend any special classes or implement any special interfaces (ie. Spring controllers, Struts), and some of the code has been left out for brevity's sake.
The question I have is how the unittest should be written. In the above unit test, he is calling both the addHandler(...) and getHandler(...) methods from within the same test. Now, as a general rule of thumb, shouldn't he be testing out only the addHandler(...) method if he's testing the adding functionality? Doesn't this particular unit test incorrectly assume that getHandler() works correctly? Imagine if a unit test called, say, 5 different methods on an object. If the test fails, you don't know if the problem is coming from method1 or method2 or method3, etc. I mean if I were asked to come up with a unit test that tested addHandler(), mine would look like:
The problem is that to test getHandler in isolation, you need to have access to the requestHandlers map, which you probably don't want to. You probably don't want to have a getRequestHandlers method, otherwise you'd end up with getters for everything. The only way to have something in the requestHandlers is to add handlers via addHandler. I think that the test would be better if there were more than one handler added. It would test both add and get in the same function.
In one test method, I don't think that you are limited to one call of the object you are testing. I'm not shocked to see both add and get tested here. As long as all the branches are tested, I think that's fine.