Nullpointer on Mockito when

2019-06-27 12:45发布

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";
                }
            });

I get a nullpointer on the line Mockito.when, what is wrong?

2条回答
一夜七次
2楼-- · 2019-06-27 12:56

You need another mock...

connectionMock.createStatement()

...will return null unless you set up an expectation for it.

For example, add...

@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);

Update #2

Removed stuff that was wrong

查看更多
手持菜刀,她持情操
3楼-- · 2019-06-27 12:56

Actually, you can have a better usage about Mockito:

@RunWith(MockitoJUnitRunner.class)
 public class ExampleTest {
     @Mock
     public Connection connectionMock;     
 }
查看更多
登录 后发表回答