From b3f370528665d89e8b5aeda26e33c606029ca170 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Tue, 21 Jul 2009 12:12:42 +0000 Subject: [PATCH] [SPR-5944] Documented potential "false positives" in ORM test code. --- spring-framework-reference/src/testing.xml | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/spring-framework-reference/src/testing.xml b/spring-framework-reference/src/testing.xml index 840fbfc20a..d2fbaa087e 100644 --- a/spring-framework-reference/src/testing.xml +++ b/spring-framework-reference/src/testing.xml @@ -1396,6 +1396,41 @@ public class FictitiousTransactionalTest { // logic which does not modify database state } } + + + Avoid false positives when testing ORM code + When testing code involving an ORM framework such as JPA + or Hibernate, it is a good practice to + flush the underlying session within test + methods which update the state of the session. Failing to flush + the ORM framework's underlying session can lead to + false positives: your test may pass, but + the same code will throw an exception in a live, production + environment. In the following Hibernate-based example test case, + we have two methods: one which demonstrates a false positive + and one which correctly exposes the results of flushing the + session. + + ... +@Autowired +private SessionFactory sessionFactory; + +@Test // no expected exception! +public void falsePositive() { + updateEntityInHibernateSession(); + // False positive: an exception will be thrown once the session is + // finally flushed (i.e., in production code) +} + +@Test(expected = GenericJDBCException.class) +public void updateWithSessionFlush() { + updateEntityInHibernateSession(); + // Manual flush is required to avoid false positive in test + sessionFactory.getCurrentSession().flush(); +} +... + +