如何使用mockito模拟JPA for Post方法

时间:2017-09-18 18:25:39

标签: spring rest jpa mockito

我试图为使用JPA作为DAO Layer的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);

}

3 个答案:

答案 0 :(得分:0)

你有一个本地模拟expected,你试图在assertEquals()中使用,但是这将永远不会起作用,因为assertEquals使用Object.equals,而Mockito劫持equals用于内部使用。除了自己,Mockito模拟永远不会Object.equals

答案 1 :(得分:0)

我们遇到类似的NullPointerException问题,这是因为实体管理器。在我们更新setUp方法中的连接属性后,我们可以调用JPA。

您可以尝试设置类似的连接属性。

    //declare emfactory 
    private static EntityManagerFactory emfactory;
    private static EntityManager em;

    @BeforeClass
    public static void setUp() throws Exception{
           Map<Object, Object> properties = new HashMap<Object, Object>();
           properties.put("openjpa.ConnectionURL", 
                  "jdbc:db2://yourserver:port/DBName");
           properties.put("openjpa.ConnectionUserName", "username");
           properties.put("openjpa.ConnectionPassword", "userpassword");
           //set Schema

           //set Driver Name

           emfactory = Persistence.createEntityManagerFactory("PersistenceUnitName", 
                              properties);
           em = emfactory.createEntityManager();
           Mockito.when(emf.createEntityManager()).thenReturn(em);
     }

另外,您需要修改test_create_employee_success()以使其正常工作。你在这个方法中嘲笑一切,你不应该这样做。你可以尝试这样的事情。

    @Test
    public void test_create_employee_success() throws Exception {
    {
         InputEntity inputEntity = new InputEntity();
         employeeService.create(inputEntity);
    }

答案 2 :(得分:0)

您需要在代码中进行以下更改:

1.而不是

@Autowired
EmployeeService employeeService;

您可以使用:

@InjectMocks
private EmployeeService EmployeeService;
  1. 同样正如你在方法中嘲笑 - InputEntity expected = Mockito.mock(InputEntity .class);除非在其他一些方法中使用,否则你不需要在班级这个声明。

  2. 你也可以摆脱声明 -

    InputEntity actual = new InputEntity();

    您无法使用new关键字断言模拟对象和对象。

  3. 清洁单元测试将如下所示 -

    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.EntityTransaction;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.InjectMocks;
    import org.mockito.Mock;
    import org.mockito.Mockito;
    import org.mockito.runners.MockitoJUnitRunner;
    
    @RunWith(MockitoJUnitRunner.class)
    public class EmployeeServiceImplTest {
    
        @Mock
        private EntityManager em;
    
        @Mock
        private EntityManagerFactory emf;
    
        @InjectMocks
        private EmployeeService EmployeeService;
    
        @Mock
        private EntityTransaction et;
    
        @Test
        public void testCreate() throws Exception {
            InputEntity expected = Mockito.mock(InputEntity.class);
            Mockito.when(em.getTransaction()).thenReturn(et);
            Mockito.when(emf.createEntityManager()).thenReturn(em);
            EmployeeService.create(expected);
            Mockito.verify(em, Mockito.times(1)).persist(expected);
        }
    
    }