Java Reference
In-Depth Information
Listing 8.9. A Spring test case for the JPA DAO implementation
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
@Transactional
public class JpaProductDAOTest {
@Autowired
private ProductDAO dao;
@Test
public void testFindById() {
Product p = dao.findProductById(1);
assertEquals("baseball", p.getName());
}
@Test
public void testGetAllProducts() {
List<Product> products = dao.getAllProducts();
assertEquals(3, products.size());
}
@Test
public void testInsert() {
Product p = new Product(99, "racketball", 7.99);
int id = dao.insertProduct(p);
Product p1 = dao.findProductById(id);
assertEquals("racketball", p1.getName());
}
@Test
public void testDelete() {
List<Product> products = dao.getAllProducts();
for (Product p : products) {
dao.deleteProduct(p.getId());
}
assertEquals(0, dao.getAllProducts().size());
}
}
The tests check each of the DAO methods. My favorite is testDelete , which deletes
every row in the table, verifies that they're gone, and doesn't add them back in , which has
the side effect of giving any DBAs heart palpitations. Fortunately, Spring rolls back all the
changes when the test is finished, so nothing is lost, but a good time is had by all.
The last piece of the puzzle is the Maven build file. You can see it, as usual, in the topic
source code.
Search WWH ::




Custom Search