我使用以下测试来测试我的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";
}
});
我在Mockito这条线上得到了一个nullpointer。什么错了?
答案 0 :(得分:5)
你需要另一个模拟......
connectionMock.createStatement()
...除非您为它设置期望,否则将返回null。
例如,添加...
@Mock
private Statement statement;
...
when(connectionMock.createStatement()).thenReturn(statement);
when(statement.executeQuery(sql)).thenAnswer(...);
要回答下面的评论,您应该返回结果集,而不是字符串。例如......
@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
删除了错误的内容
答案 1 :(得分:0)
实际上,你可以更好地使用Mockito:
@RunWith(MockitoJUnitRunner.class)
public class ExampleTest {
@Mock
public Connection connectionMock;
}