I'm trying to write a Unit test using TestNG to save test data to a db. I'm using DataProvider for creating test data as below:
@DataProvider
private Object[][] movieTitles() {
return new Object[][] {
new String[] { "Golden Eye" },
new String[] { "Troy" }, new String[] { "Gladiator" },
new String[] { "Ring" }, new String[] { "The Village" } };
}
And my test case is using try-with-resources as below:
@Test(dataProvider = "movieTitles")
public void save(String title) {
EntityTransaction tx = null;
try(PersistenceUtil util = PersistenceUtil.getUtil()){
Movie movie = new Movie(title);
EntityManager em = util.getManager();
tx = util.getTransaction();
tx.begin();
em.persist(movie);
tx.commit();
Assert.assertTrue(movie.getId() > 0);
} catch (Exception e) {
if(tx.isActive())
tx.rollback();
e.fillInStackTrace();
return;
}
}
The first data is saved successfully. However, the PersistenceUtil in the try block is not created/initialized again and thus EntityTransaction is null. And thus a NPE exception occurs for the rest of the data. Why is PersistenceUtil not initialized again in the try-with-resources block. Is there anyway to achieve the same?
The bug has nothing to do with automatic resource management. The
try
block will executegetUtil()
each time thesave()
method is called.The problem lies in the
PersistenceUtil
class;getUtil()
is returning a non-nullPersistenceUtil
, but it's not behaving properly, and returnsnull
fromgetTransaction()
.