Jil*_*ill 0 junit entitymanager junit4
Mockito.when为下面的代码行获取空指针异常。
when(entityManager.createQuery(any(String.class)).setParameter(any(String.class), any(String.class)).getSingleResult()).thenReturn("2");
Run Code Online (Sandbox Code Playgroud)
试图模拟声明为的实体管理器
@Mock
private EntityManager entityManager;
Run Code Online (Sandbox Code Playgroud)
任何帮助解决这个问题?
完成测试类
@RunWith(MockitoJUnitRunner.class)
public class ASDAOImplTest {
@InjectMocks
ASDAOImpl asdaoImpl=new ASDAOImpl();
@Mock
private EntityManager entityManager;
@Before
public void setUp()
{
ReflectionTestUtils.setField(asdaoImpl,"capLimit", 1);
}
@Test
@Ignore
public void validateCappingTest()
{
when(entityManager.createQuery(any(String.class)).setParameter(any(String.class), any(String.class)).getSingleResult()).thenReturn("2");
asdaoImpl.validateCapping("2");
}
}
Run Code Online (Sandbox Code Playgroud)
Edit: Ah, spoke to soon. The error is here...
when(entityManager.createQuery(any(String.class)).setParameter(...)
Run Code Online (Sandbox Code Playgroud)
entityManager is a mock. Per default, a mock will return null. So, entityManager.createQuery(...) will return null. Calling setParameter on null is a NPE.
What you need to insert is a query mock...
@Mock
private Query query;
...
// when createQuery is called, return the mocked query object (instead of null)
when(entityManager.createQuery(any(String.class)).thenReturn(query);
// make sure that setParameter returns this query object back (would otherwise also be NPE)
when(query.setParameter(any(String.class), any(String.class)).thenReturn(query);
// And return the desired result from getSingleResult
when(query.getSingleResult()).thenReturn("2");
Run Code Online (Sandbox Code Playgroud)
Old answer:
Hard to say without the complete code, but a guess would be that you are misssing the Mockito initialization (the part that actually creates object for the variables annotated with @Mock). This can be done in at least two ways:
// Run the whole test with the Mockito runner...
@RunWith(MockitoJUnitRunner.class)
public class MyTestClass { ...
Run Code Online (Sandbox Code Playgroud)
or...
// Do the Mockito initialization "manually"
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
Run Code Online (Sandbox Code Playgroud)
Both ways will lead to Mockito creating all the objects where the variables are annotated with @Mock (it also handles @InjectMocks, etc.).
If this doesn't help, you will have to post more of your test class, otherwise probably noone can help.
| 归档时间: |
|
| 查看次数: |
4789 次 |
| 最近记录: |