4 java nullpointerexception mockito
我使用以下测试来测试我的utitiliesclass,我使用mockito进行sql连接.
@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";
}
});
Run Code Online (Sandbox Code Playgroud)
我在Mockito线上得到了一个nullpointer.什么是错的?
你需要另一个模拟......
connectionMock.createStatement()
Run Code Online (Sandbox Code Playgroud)
...除非你设定了它的期望,否则将返回null.
例如,添加...
@Mock
private Statement statement;
...
when(connectionMock.createStatement()).thenReturn(statement);
when(statement.executeQuery(sql)).thenAnswer(...);
Run Code Online (Sandbox Code Playgroud)
要回答下面的注释,您应该返回结果集,而不是字符串.例如...
@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);
Run Code Online (Sandbox Code Playgroud)
更新#2
删除了错误的东西