user4717008
user4717008

Reputation:

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?

Upvotes: 5

Views: 1843

Answers (3)

Tom Carmi
Tom Carmi

Reputation: 594

You can try to use RETURNS_DEEP_STUBS;

In your code it would look something like that:

    public Connection connectionMock;

    @Before
    public void setUp(){
        connectionMock = Mockito.mock(Connection.class, RETURNS_DEEP_STUBS);
    }
    
    ...

Upvotes: 0

BretC
BretC

Reputation: 4199

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

Upvotes: 5

Yang Dong
Yang Dong

Reputation: 490

Actually, you can have a better usage about Mockito:

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

Upvotes: -1

Related Questions