我在查询对象上遇到问题,即使我用查询模拟对象将其存根,它也会变为空。这就是代码
Query query = getEntityManager().createNativeQuery(queryString, SomeRandom.class); return query.getResultList(); //-->This is where I get the error, the query object is null.我的测试方法是
Query query = mock(Query.class); when(entityManager.createNativeQuery("", SomeRandom.class)).thenReturn(query); List<SomeRandom> someList = requestDao.getSomeList(parameter, parameter, parameter, parameter);I am having a problem on my query object, it becomes null even though I stub it with a query mock object.. This is the code
Query query = getEntityManager().createNativeQuery(queryString, SomeRandom.class); return query.getResultList(); //-->This is where I get the error, the query object is null.my Test method is
Query query = mock(Query.class); when(entityManager.createNativeQuery("", SomeRandom.class)).thenReturn(query); List<SomeRandom> someList = requestDao.getSomeList(parameter, parameter, parameter, parameter);最满意答案
这可能意味着您传递给mocked方法的其中一个匹配器不匹配。 您传递了一个实际的String实例(空字符串),它在引擎盖下转换为Equals匹配器 。 您的示例仅在queryString也是空字符串时才有效。
这应匹配任何查询字符串:
when(entityManager.createNativeQuery(anyString(), eq(SomeRandom.class))) .thenReturn(query);这是你期望传递的一些具体的字符串:
String expectedQueryString = "select 1"; when(entityManager.createNativeQuery(expectedQueryString, SomeRandom.class)) .thenReturn(query);根据评论进行编辑:
如果从eq(SomeRandom.class)更改为any()解决了问题,则eq(SomeRandom.class)匹配器不匹配,这意味着SomeRandom.class不是实际传递给mocked方法的。
This probably means that one of the matchers that you passed to the mocked method did not match. You passed an actual String instance (the empty string), which is transformed under the hood into an Equals matcher. Your example would only work if queryString was the empty string as well.
This should match on any query string:
when(entityManager.createNativeQuery(anyString(), eq(SomeRandom.class))) .thenReturn(query);And this on some concrete String that you expect to be passed:
String expectedQueryString = "select 1"; when(entityManager.createNativeQuery(expectedQueryString, SomeRandom.class)) .thenReturn(query);Edit based on comment:
If changing from eq(SomeRandom.class) to any() solved the problem, then the eq(SomeRandom.class) matcher did not match, which means SomeRandom.class was not what was in fact passed to the mocked method.
更多推荐
发布评论