Next, let's test the save operation. In our case, we would like to test two scenarios. One is the
normal situation in which a valid contact is saved successfully, and the other is a contact have an error
that should cause the correct exception being thrown. Listing 19-13 shows the code snippet for the two
test cases.
Listing 19-13. Testing the Save Operation
package com.apress.prospring3.ch19.service.jpa;
import javax.validation.ConstraintViolationException;
// Other import statements omitted
public class ContactServiceImplTest extends AbstractServiceImplTest {
// Other code omitted
@Test
public void testAddContact() throws Exception {
// Clear all existing data in Contact table
deleteFromTables("CONTACT");
Contact contact = new Contact();
contact.setFirstName("Rod");
contact.setLastName("Johnson");
contact = customerService.save(contact);
em.flush();
List<Contact> contacts = customerService.findAll();
assertEquals(1, contacts.size());
}
@Test(expected=ConstraintViolationException.class)
public void testAddContactWithJSR303Error() throws Exception {
// Clear all existing data in Contact table
deleteFromTables("CONTACT");
Contact contact = new Contact();
contact = customerService.save(contact);
em.flush();
List<Contact> contacts = customerService.findAll();
assertEquals(0, contacts.size());
}
}
In Listing 19-13, take a look at the testAddContact() method. Within the method, to ensure that no
data exists in the CONTACT table, we call the convenient method deleteFromTables() provided by the
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home