在junit中运行方法时InvocationTargetException

时间:2018-07-12 13:07:29

标签: java unit-testing junit mockito hibernate-entitymanager

我得到一个NullPointer异常,并且在调试代码时得到了InvocationTargetException。我不知道我要去哪里错了。有人可以帮我解决这个问题!

for ele in hng_row:
    if not ele.isdigit() and not ele.isalpha() and not ele.isalnum():
        if (ele.endswith('.00')
                or ele.startswith('0.') and ele.endswith('0') and ele != '0.0'
                or (ele[-2] != '0') and (ele[-2] != '.') and (ele[-1] == '0')):
            get_index = hng_row.index(ele)
            ele = ele[:-1]
            hng_row[get_index] = ele

这是我的Junit:

 @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'";

       //getting an InvocationTargetException here while debugging as junit
       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;
}

试图找到解决方案并解决了很久!

1 个答案:

答案 0 :(得分:0)

这可能是因为您在模拟createQuery方法中仅使用String作为参数,而实际上在您的方法中却在使用String以及类参数调用createQuery方法。 在测试方法中模拟具有正确签名的方法。

第二,您的测试方法中没有断言语句或验证,您究竟要测试什么?