Testing with JUnit
You can use JUnit to create test cases to validate your JPA mappings.
-
Create a JUnit
@BeforeAllmethod that initializes anEntityManagerFactorywhich we will use to createEntityManagerobjects. -
Create JUnit
@BeforeEachand@AfterEachmethods to initialize and close anEntityManagerobject.
As the names imply, your @BeforeEach method is invoked before each test and your @AfterEach method runs after each test.
Create individual @Test methods to verify your mappings result in values in line with your expectations.
Drill¶
We are going to create a JUnit test for our Customer entity.
- In the
entitiespackage in src/test/java, create a new JUnit Jupiter test case namedCustomerTest.java.Create method stubs for
setUpBeforeClass(),tearDownAfterClass,setUp(), andtearDown().Include the JUnit assertion library:
import static org.junit.jupiter.api.Assertions.*;
- Add two private fields to the newly created class:
private static EntityManagerFactory emf; private EntityManager em;
- Use
@BeforeAlland@AfterAllto initialize and close theEntityManagerFactory.@BeforeAll static void setUpBeforeClass() throws Exception { emf = Persistence.createEntityManagerFactory("VideoStore"); } @AfterAll static void tearDownAfterClass() throws Exception { emf.close(); }
- Use
@BeforeEachand@AfterEachto initialize and close theEntityManager.@BeforeEach void setUp() throws Exception { em = emf.createEntityManager(); } @AfterEach void tearDown() throws Exception { em.close(); }
- Run the test by right clicking on the test in Eclipse's Project Explorer and choosing Run As -> JUnit Test.
- If everything is configured correctly, the test should run and the
test()stub should cause anAssertionFailedError.If you get a
PersistenceExceptionor some other error, check your persistence unit name and other configuration and resolve the issue before continuing.Write tests.
- Change the method
testtotest_Customer_mappingsand remove thefailmethod. Add code to find the Customer entity with id of 1, and callassertEquals()to verify that each field contains expected values. The expected values are in thecustomertable in the database, so you will find these values by querying the database via the command line.
- Run the test and make any changes necessary until it passes.
Practice Exercise¶
The order in which you close these resources does matter. Closing
emfbeforeemwould throw an exception. Can you guess why?
