Question

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?

Was it helpful?

Solution

The bug has nothing to do with automatic resource management. The try block will execute getUtil() each time the save() method is called.

The problem lies in the PersistenceUtil class; getUtil() is returning a non-null PersistenceUtil, but it's not behaving properly, and returns null from getTransaction().

OTHER TIPS

Check whether you persistence layer stays live after util.close() has been called at the end of the try-with-resources.

Note also that you can simplify the Object matrix creation:

public class Main {

   static Object[][] array = {  { "a", "b" } , { "c", "d" } } ;

   // test print
   public static void main(String[] argv) {
      for (int i=0;i<array.length;i++) {
         Object[] sub = array[i];
         for (int j=0;j<sub.length;j++) {
            System.out.println(sub[j]);
         }
      }
   }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top