用于存储库层EntityManager链式方法的Mockito测试用例

时间:2018-12-13 07:30:45

标签: spring-boot intellij-idea mockito testng entitymanager

要使用Mockito测试的存储库代码:

public List<X> findAll() {

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<X> criteriaQuery = criteriaBuilder.createQuery(X.class);
Root<X> policyRoot = criteriaQuery.from(X.class);

return entityManager.createQuery(criteriaQuery.select(policyRoot)).getResultList();

}

如何模拟entityManger的cretedQuery()和getResultList()方法?

@Test
public void testCase() {
when(entityManager.getCriteriaBuilder()).thenReturn(new 
CriteriaBuilderImpl(any()));

Query query = new QueryImpl(any(), any(), any());
when(entityManager.createQuery(anyString())).thenReturn(query);
when(query.getResultList()).thenReturn(attributeList);

}

它抛出NullPointerException。

1 个答案:

答案 0 :(得分:0)

使用模拟。确保entityManager在您要测试的类中是可注入的。对于单元测试,我肯定会像这样进行测试。它不会测试数据库,但是会测试所有已完成的调用和常规应用程序逻辑。我同意您还应该编写一个集成测试,以测试“实际”数据库调用和结果。

@RunWith(MockitoJUnitRunner.class)
public class QueryTest {
    @Mock
    TypedQuery<X> query;

    @Mock
    CriteriaBuilderImpl criteriaBuilder;

    @Mock
    CriteriaQuery<X> criteriaQuery;

    @Mock
    Root<X> policyRoot;

    @Mock
    EntityManager manager; // This mock should be injected in the class that is been tested

    @InjectMocks
    TestClass sut; //System Under Test

    @Test
    public void test() {
        when(manager.getCriteriaBuilder()).thenReturn(criteriaBuilder);
        when(criteriaBuilder.createQuery(any(X.class)).thenReturn(criteriaQuery);
        when(criteriaQuery.from(any(X.class)).thenReturn(policyRoot);
        when(criteriaQuery.select(eq(policyRoot))).thenReturn(criteriaQuery);
        when(manager.createQuery(eq(criteriaQuery)).thenReturn(query);
        when(query.getResultList()).thenReturn(Collections.emptyList());

        List<X> result = sut.findAll();

        // now verify
        verify(manager, times(1)).getCriteriaBuilder();
        verify(criteriaBuilder, times(1)).createQuery(any(X.class));
        // and so on

        // now write your assertions
        assertEquals(0, result.getSize());
    }
}