我正在構建一個JEE EAR應用程序,並開始使用EasyMock爲我的服務正在使用的存儲庫創建模擬。但我不確定結果是否正確。特別是在我測試void方法的兩個測試中。EasyMock我做對了嗎?
public class VenueServiceTest extends ServiceTest {
private VenueService venueService = new VenueServiceImpl();
private VenueRepository mockVenueRepository; // interface that the service is using
private List<Venue> venues;
private Venue venue1;
private Venue venue2;
@Override
public void setupMock() {
venues = MockUtils.getMockedVenues();
venue1 = venues.get(0);
venue2 = venues.get(1);
mockVenueRepository = createMock(VenueRepository.class);
venueService.setRepository(mockVenueRepository);
}
@Override
public void testUpdate() {
Venue originalVenue = new Venue(0L, "The Venue");
String originalName = originalVenue.getName();
mockVenueRepository.update(originalVenue);
expect(mockVenueRepository.findById(originalVenue.getId())).andReturn(originalVenue);
replay(mockVenueRepository);
originalVenue.setName("Another Venue");
venueService.updateEntity(originalVenue);
Venue newVenue = venueService.getEntity(originalVenue.getId());
String newName = newVenue.getName();
assertFalse("Venue names should not be equal", originalName.equals(newName));
verify(mockVenueRepository);
}
@Override
public void testDelete() {
expect(mockVenueRepository.findById(venue1.getId())).andReturn(venue1);
mockVenueRepository.remove(venue1);
expect(mockVenueRepository.findById(venue1.getId())).andReturn(null);
replay(mockVenueRepository);
assertNotNull(venueService.getEntity(venue1.getId()));
venueService.deleteEntity(venue1);
assertNull(venueService.getEntity(venue1.getId()));
verify(mockVenueRepository);
}
這兩個測試通過。但是如果我註釋掉他們仍然通過的刪除/更新部分。
@Override
public void testUpdate() {
Venue originalVenue = new Venue(0L, "The Venue");
String originalName = originalVenue.getName();
// mockVenueRepository.update(originalVenue);
expect(mockVenueRepository.findById(originalVenue.getId())).andReturn(originalVenue);
replay(mockVenueRepository);
originalVenue.setName("Another Venue");
// venueService.updateEntity(originalVenue);
Venue newVenue = venueService.getEntity(originalVenue.getId());
String newName = newVenue.getName();
assertFalse("Venue names should not be equal", originalName.equals(newName));
verify(mockVenueRepository);
}
@Override
public void testDelete() {
expect(mockVenueRepository.findById(venue1.getId())).andReturn(venue1);
// mockVenueRepository.remove(venue1);
expect(mockVenueRepository.findById(venue1.getId())).andReturn(null);
replay(mockVenueRepository);
assertNotNull(venueService.getEntity(venue1.getId()));
// venueService.deleteEntity(venue1);
assertNull(venueService.getEntity(venue1.getId()));
verify(mockVenueRepository);
}
我是對的嗎?我的猜測是否定的,如果是的話,你如何正確地測試?
謝謝!
你的代碼是一個有點混亂;但只是作爲初學者:嘗試使用** createStrictMock **。嚴格的嘲笑,很好,更嚴格。這使得使用它們有時更難(因爲它們堅持你指定的調用順序),但另一方面,它們是嚴格的有時正是你想要的。 – GhostCat
謝謝你的回覆。不幸的是,這並沒有解決問題。 – Johan