Mockito 上的 Nullpointer 何时

Nullpointer on Mockito when

我使用以下测试来测试我的实用程序类,我使用 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.when 上得到一个空指针,怎么了?

你需要另一个模拟...

connectionMock.createStatement()

...将 return 为 null,除非您为其设置期望值。

例如,添加...

@Mock
private Statement statement;

...

when(connectionMock.createStatement()).thenReturn(statement);
when(statement.executeQuery(sql)).thenAnswer(...);

更新

要回答下面的评论,您应该return输入结果集,而不是字符串。例如...

@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你可以有更好的用法:

@RunWith(MockitoJUnitRunner.class)
 public class ExampleTest {
     @Mock
     public Connection connectionMock;     
 }