【问题标题】:InvocationTargetException when running a method in junit在junit中运行方法时出现InvocationTargetException
【发布时间】:2018-12-20 17:42:42
【问题描述】:

我得到一个 NullPointer 异常,在调试代码时我得到一个 InvocationTargetException。我不知道我哪里错了。谁能帮我解决这个问题!

 @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;
}

这是我的 Junit:

@InjectMocks
private FinderManager classUnderTest;

private Query query;

private EntityManager emMock;

@Before
public void setUp(){
    emMock = Mockito.mock(EntityManager.class);
    query = Mockito.mock(Query.class);
    Mockito.mock(Vehicle.class);
}

@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();
}

这么久以来一直在努力寻找解决方案并解决这个问题!

【问题讨论】:

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


    【解决方案1】:

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

    其次,你的测试方法中没有断言语句或验证,你到底要测试什么?

    【讨论】:

    • 是的,这是因为他的 createQuery 方法中的类参数!这不是必需的。谢谢!
    • 如果解决方案对您有用,请接受答案:)
    猜你喜欢
    • 1970-01-01
    • 2014-06-01
    • 2019-05-29
    • 2022-12-15
    • 2014-06-15
    • 2019-03-24
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多