📄 customertest.java
字号:
package entity;
import junit.framework.JUnit4TestAdapter;
import org.junit.After;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* @author Antonio Goncalves
*/
public class CustomerTest {
private static String PERSISTENCE_UNIT_NAME = "watermelonPU";
private static Calendar calendar;
private EntityManagerFactory emf;
private EntityManager em;
private EntityTransaction trans;
public static junit.framework.Test suite() {
return new JUnit4TestAdapter(CustomerTest.class);
}
@BeforeClass
public static void initCalendar() {
calendar = GregorianCalendar.getInstance();
}
@Before
public void init() {
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = emf.createEntityManager();
trans = em.getTransaction();
}
@After
public void close() {
em.close();
emf.close();
}
@Test
public void createCustomer() {
calendar.set(1940, 10, 9);
Date dateOfBirth = calendar.getTime();
Customer customer = new Customer("John", "Lennon", "+411909", "john@lenon.com", dateOfBirth);
// Persists a customer
trans.begin();
em.persist(customer);
trans.commit();
Long id = customer.getId();
// Finds the customer by primary key
customer = em.find(Customer.class, id);
assertEquals(customer.getEmail(), "john@lenon.com");
assertEquals("Age should be 66", customer.getAge(), 66);
// Updates the customer
trans.begin();
customer.setEmail("john@beatles.co.uk");
trans.commit();
// Finds the customer by primary key
customer = em.find(Customer.class, id);
assertEquals(customer.getEmail(), "john@beatles.co.uk");
assertEquals("Age should be 66", customer.getAge(), 66);
// Deletes the customer
trans.begin();
em.remove(customer);
trans.commit();
assertNull("Customer should have been deleted", em.find(Customer.class, id));
}
@Test(expected = IllegalArgumentException.class)
public void createCustomerWithInvalidPhone() {
calendar.set(1940, 10, 9);
Date dateOfBirth = calendar.getTime();
Customer customer = new Customer("John", "Lennon", "411909", "john@lenon.com", dateOfBirth);
// Persists a customer
trans.begin();
em.persist(customer);
trans.commit();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -