简体   繁体   English

使用Junit和Mockito测试jpql查询

[英]Testing a jpql query with junit and mockito

Can someone please help me with writing a unit test case for a jpql query? 有人可以帮我写一个jpql查询的单元测试用例吗? I am new to this. 我是新来的。

This is the class to be tested. 这是要测试的类。

@Inject
private Log log;

@PersistenceContext(name = Configuration.PERSISTENT_CONTEXT)
private EntityManager em;

 public List<Vehicle> getData() {
    List<Vehicle> resultList = new ArrayList<>();

    try {
        String sql = "SELECT v FROM Vehicle v JOIN v.car c WHERE c.carType = 'BMW'";
        Query query = em.createQuery(sql, Vehicle.class);
        resultList = query.getResultList();

        if(resultList == null){
            log.error("List is empty or null");
            return null;
        }

    } catch (IllegalArgumentException ex) {
        log.info(ex.getMessage());
        log.trace(ex.getCause());
    }

    return resultList;
}

The JUnit class that I have written so far is as follows: 到目前为止,我已经编写了JUnit类,如下所示:

@InjectMocks
private FinderManager classUnderTest;

@Mock
private EntityManager emMock;

@Mock
private Query query;

@Mock
private Vehicle vehicle;

@Mock
private Car car;

@Test
public void testMethod(){
     List<Vehicle> resultList = new ArrayList<>();

    Mockito.when(emMock.createQuery(Mockito.any(String.class)))
    .thenReturn(query);

    Mockito.when(query.getResultList()).thenReturn(resultList);

    classUnderTest.getData();

}

Any help would be appreciated. 任何帮助,将不胜感激。 Thank you! 谢谢! :) :)

Try this, 尝试这个,

@Mock
private EntityManager em;

@Mock
private Vehicle vehicle;

@Mock
private Car car;

@Mock
private Query query;

@InjectMocks
private YourDAOClass yourDAOClass;

@Test
public void testMethod(){
     List<Vehicle> someList = null;


    when(em.createQuery(Mockito.anyString(), Mockito.any())).thenReturn(query);


    when(query.getResultList()).thenReturn(someList);

    assertThat(yourDAOClass.getData()).isNull()

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM