我试图编写使用JPA作为DAO层的Create(Post)方法的单元测试。对于Mockito而言,我是新手,因此需要提供洞察。如何使用mockito模拟Post方法的JPA
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是实体类的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);
}
欣赏使用您的见解.I'm实际上JPA春天开机,因此在创建设置类的实体管理器还是给了我一个问题。因此,我尝试用@asg模拟DataSource,好像现在一样,从长远来看,我必须尝试测试真实的源代码。 – DinaMike