Essentially is a question about a JUnit test where you create an entity in the @Before method but you can’t find it in the actual test method. I’ve been trying to find out what’s going on, and any kind of help would be really appreciated.
Essentially it’s a JUnit class like this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"myConfiFile.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class DummyTest {
@Before
public void setUp() {
// Create an entity here and call .save()
}
@Test
public void testCountMsisdnNumberPlans() {
int howManyInstances = dao.countInstancesOfEntity();
}
}
The DAO code is quite simple:
@Transactional(readOnly = true)
public Integer countInstancesOfEntity(Integer idhlr) {
return ((BigDecimal) em.createNativeQuery("SELECT COUNT(*) FROM ENTITY")
.getSingleResult()).intValue();
}
In the setUp() we create one entity but the DAO code keeps returning 0. Any comment would be really great.
Thanks.
SpringJUnit4ClassRunnerexecutes@Beforeand@Afterinside the same transaction as the test method. Thus, changes made in persistence context in@Beforeare not flushed to the database before running the test method. Implicit flush before executing a query doesn’t happen as well, because transaction is configured as read only.So, you have several options:
readOnly = true, it should enable automatic flush before executing the queryflush()to@Before, it should force flush even if transaction is read only@BeforeTransactioninstead of@Before. Note that this method runs outside of transaction, so that it’s not affected bydefaultRollbacksetting, and requires manual transaction management.