Java Reference
In-Depth Information
the case in this example), eventually more will be added, so it's worth having such a
setup method from the beginning.
Then, on the test case we create a User object E and set the mock expectation F
to return it when requested (see more about mock expectations in chapter 6). Notice
that newUser() belongs to EntitiesHelper , which provides methods to create new
entities (like User ) and assert the properties of existing ones ( EntitiesHelper was
introduced in chapter 17, and new methods are added in this chapter; the full code
isn't listed here but is available for download).
Finally, on G the method being tested is called, and the result is checked on H
(which is another method defined in EntitiesHelper ).
This test case seems pretty much complete, and it almost is, except that it exercises
only the best-case scenario. But what if the DAO didn't find the request user? To be
complete, the test cases must also exercise negative scenarios. Let's try to add a new
test case that simulates the DAO method returning null : 4
@Test
public void testGetUserByIdUnknownId() {
int id = 666;
expect(dao.getUserById(id)).andReturn(null);
replay(dao);
UserDto dto = facade.getUserById(id);
assertNull(dto);
}
Running this test, we get the dreaded NPE ( NullPointerException ):
java.lang.NullPointerException
at com.manning.junitbook.ch18.business.UserFacadeImpl.getUserById
(UserFacade Impl.java:49)
at com.manning.junitbook.ch18.business.UserFacadeImplTest.testGetUserById
UnkownId(UserFacadeImplTest.java:51)
This makes sense, because the Facade method isn't checking to see if the object
return by the DAO is null . It could be fixed by adding the following lines after the
user is retrieved from the DAO :
if ( user == null ) {
return null;
}
Once this test case is added and the method fixed, our Facade is complete and fully
tested, without needing a DAO implementation.
Such separation of functionalities in interfaces and implementations greatly
facilitates the development of multilayered applications, because each layer can be
4
How do we know the DAO returns null in this case? And who defined what the Facade should return? What
happens in these exceptional cases should be documented in the DAO and Facade methods' Javadoc, and
the test cases should follow that contract. In our example, we don't document that on purpose, to show how
serious that lack of documentation can be. Anyway, we're returning null in both cases, but another approach
could be throwing an ObjectNotFoundException .
 
 
 
Search WWH ::




Custom Search