Search code examples
javanullpointerexceptionmockito

Nullpointer on Mockito when


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?


Solution

  • 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