Java Reference
In-Depth Information
including EasyMock [EasyMock] and jMock [jMock]. EasyMock and jMock are both
extensions to JUnit, and provide classes for creating and configuring mock objects.
Let's look at a simple example of how to use jMock, which is my personal favorite
since it appears to be a little more flexible than the others. Imagine you needed to
write a test for PlaceOrderService.updateRestaurant() , which calls RestaurantRe-
pository.findRestaurant() . Instead of hand-coding a fake RestaurantRepository ,
you use jMock to create a mock RestaurantRepository and configure it to expect
its findRestaurant() method to be called. jMock will throw an exception if either
some other method was called unexpectedly or the expected method was not called.
Listing 3.1 shows an excerpt of a test case for PlaceOrderService that does this.
Listing 3.1
An example of a test case that uses jMock
public class PlaceOrderServiceTests
extends MockObjectTestCase {
private Mock mockRestaurantRepository;
private Restaurant restaurant;
private PlaceOrderService service;
B
public void setUp() {
mockRestaurantRepository =
new Mock(RestaurantRepository.class);
RestaurantRepository restaurantRepository =
(RestaurantRepository)mockRestaurantRepository.proxy();
service =
new PlaceOrderServiceImpl(restaurantRepository);
restaurant = new Restaurant();
}
C D
E
public void testUpdateRestaurant_good() throws Exception {
mockRestaurantRepository.expects(once())
.method("findRestaurant")
.with(eq(restaurantId))
.will(returnValue(restaurant));
PlaceOrderServiceResult result
= service.updateRestaurant(
pendingOrderId,
restaurantId);
}
F
G
 
 
 
Search WWH ::




Custom Search