【发布时间】:2018-02-27 09:08:38
【问题描述】:
我正在尝试为使用 JPA 作为 DAO 层的 Create(Post) 方法编写单元测试。我是 Mockito 的新手,因此需要洞察力。
1.EmployeeService .java
@Component("IEmployeeService ")
public class EmployeeService implements IInputService {
@Inject
EntityManagerFactory emf;
@PersistenceContext
EntityManager em;
public InputEntity create(InputEntity inputEntity) {
em = emf.createEntityManager();
try {
em.getTransaction().begin();
inputEntity.setLST_UPDTD_TS(new Date());
inputEntity.setLST_UPDTD_USER_ID(new String("USER1"));
em.persist(inputEntity);
em.getTransaction().commit();
} catch (PersistenceException e)
{
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
throw new WebApplicationException(e,Response.Status.INTERNAL_SERVER_ERROR);
}
finally {
em.close();
}
return inputEntity;
}
2.InputEntity.java 是 Entity 类,具有 getter 和 setter,用于对应列的员工年龄、薪水等。
现在,如果调用 Post 方法,将调用 EmployeeService 类中的 create 方法。我必须使用 mockito 编写一个单元测试,并且我得到空指针,下面是我编写的测试。
@Category(UnitTest.class)
@RunWith(MockitoJUnitRunner.class)
public class EmployeeServiceTest {
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Autowired
EmployeeService employeeService;
@Mock
InputEntity inputEntity;
@Mock
EntityManagerFactory emf;
@Mock
private EntityManager em;
@Mock
private EntityTransaction et;
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void test_create_employee_success() throws Exception {
InputEntity expected = Mockito.mock(InputEntity .class);
Mockito.when(em.getTransaction()).thenReturn(et);
Mockito.when(emf.createEntityManager()).thenReturn(em);
Mockito.doReturn(expected).when(employeeService).create(inputEntityMock);
InputEntity actual = new InputEntity();
Mockito.doReturn(actual).when(employeeService).create(inputFileRoleValidationMock);
assertEquals(expected, actual);
}
【问题讨论】: