All your database related unit tests for a play 2 java application have to handle the fakeApplication startup, load an fresh in memory database and load the test related fixtures. You need fixy and this helper to do the trick:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | public class ModelTest { public FakeApplication app; public Fixy fixtures; EntityManager em = null; EntityTransaction tx = null; @Before public void beforeEachTest() { startFakeApp(); loadFixtures(); openTransaction(); } @After public void afterEachTest(){ closeTransaction(); stopFakeApp(); } // template method to load fixtures public List< String> fixturesToLoad() { return new ArrayList< String>(); } private void startFakeApp() { app = Helpers.fakeApplication(Helpers.inMemoryDatabase()); Helpers.start(app); } private void stopFakeApp(){ Helpers.stop(app); } private void openTransaction() { em = JPA.em("default"); JPA.bindForCurrentThread(em); tx = em.getTransaction(); tx.begin(); } private void closeTransaction() { if(tx != null) { if (tx.isActive()){ if(tx.getRollbackOnly()) { tx.rollback(); } else { tx.commit(); } } } JPA.bindForCurrentThread(null); if(em != null) { em.close(); } } private void loadFixtures() { openTransaction(); fixtures = new JpaFixyBuilder(JPA.em()).build(); fixtures.load(addPathAndPrefix(fixturesToLoad())); closeTransaction(); } private static String[] addPathAndPrefix(List< String> names){ List< String> fixtureNames = new ArrayList<>(); for (String name : names){ fixtureNames.add("fixtures/" + name + ".yaml"); } return fixtureNames.toArray(new String[0]); } } |
To use the helper you just have to extend from ModelTest and override the fixturesToLoad method:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class TaskTest extends ModelTest { @Override public List< String> fixturesToLoad() { return Arrays.asList("tasks"); } @Test public void testFindByName(){ Task task = Task.findByName("Task 1"); assertEquals("Task 1", task.name); } } |
The tasks.yaml loaded in fixturesToLoad must be placed in the conf/fixtures folder of the play application.
The source code is pushed to Play4Jpa repo on github.
Information about Data protection