Home
Creating a JUnit test case for a JPA entity
To create a JUnit test case for a JPA entity, do the following steps:
![]()
Create a new package called itso.rad75.bank.test.junit.jpa under RAD75JUnit/src.
![]()
Right-click the itso.rad75.bank.test.junit.jpa package and select New Æ JUnit Test Case (only available in the Java perspective), or select New Æ Other Æ Java Æ JUnit Æ JUnit Test Case, or click the arrow in the icon in the toolbar and select
.
![]()
In the New JUnit Test Case dialog, select New JUnit 4 test, type AccountJPATest as Name, select setUp and tearDown methods, and click Finish (Figure | 3-5).
![]()
Figure 23-5 JUnit Test Case Wizard
![]()
Implement the AccountJPATest class as shown in Example | 3-6. The code is available in c:\7672code\junit\jpa\AccountJPATest.java. Example 23-6 JUnit test case for JPA
package itso.rad75.bank.test.junit.jpa;import ......public class AccountJPATest {EntityManager em;@Beforepublic void setUp() throws Exception {if (em == null) {em = Persistence.createEntityManagerFactory("RAD75JPA").createEntityManager();}}@Afterpublic void tearDown() throws Exception {if (em != null) {em.close();}}@Testpublic void testLoadAccount() {try {Account ac = em.find(Account.class, "001-111001");assertNotNull(ac);} catch (Exception e) {fail("Error: Account not found!");e.printStackTrace();}}}
![]()
ibm.com/redbooks