Mockito 上的空指针 [英] Nullpointer on Mockito when
本文介绍了Mockito 上的空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下测试来测试我的实用程序类,我使用 mockito 进行 sql 连接.
I use following test to test my utitiliesclass, I use mockito for the sql connection.
@Mock
public Connection connectionMock;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
@Test
public void testResource(){
String sql = Utilities.resourceToString("testSql.sql");
try {
Mockito.when(connectionMock.createStatement().executeQuery(sql)).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocationOnMock) throws Throwable {
return "X";
}
});
我在 Mockito.when 线上得到一个空指针,怎么了?
I get a nullpointer on the line Mockito.when, what is wrong?
推荐答案
你需要另一个模拟...
You need another mock...
connectionMock.createStatement()
...将返回 null,除非您为其设置期望值.
...will return null unless you set up an expectation for it.
例如添加...
@Mock
private Statement statement;
...
when(connectionMock.createStatement()).thenReturn(statement);
when(statement.executeQuery(sql)).thenAnswer(...);
更新
要回答下面的评论,您应该返回结果集,而不是字符串.例如...
Update
To answer the comment below, you should be returning a result set, not a string. For example...
@Mock
private ResultSet resultSet;
...
when(statement.executeQuery(sql)).thenReturn(resultSet);
when(resultSet.getString(1)).thenReturn("X");
... call the class under the test...
// Add verification that "next" was called before "getString"...
// (not 100% necessary, but makes it a more thorough test)
InOrder order = inOrder(resultSet);
order.verify(resultSet).next();
order.verify(resultSet).getString(1);
更新 #2
删除错误的内容
这篇关于Mockito 上的空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文