Tausif Shakeel
Tausif Shakeel

Reputation: 83

Mocking resultset getTimeStamp doesn't work for more thans 1 row

I am trying to mock a java.sql.resultset in my unit test case. I am using mocikto and junit for assertions. All the call to next and getString being mocked work properly, but when i try to mock getTimestamp it works only for first row i.e first resultset.

when(statement.getResultSet()).thenReturn(resultSet);
    when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
    when(resultSet.getString("HIST_ID"))
   .thenReturn("").thenReturn("").thenReturn("").thenReturn("").thenReturn("");
when(resultSet.getTimestamp("CREATED_ON")).thenReturn(Timestamp.valueOf("2017-02-06 14:16:39.78"))
.thenReturn(Timestamp.valueOf("2017-02-08 11:29:31.3"))
.thenReturn(Timestamp.valueOf("2017-02-08 11:29:57.49"))
.thenReturn(Timestamp.valueOf("2017-02-08 11:30:13.47"))
.thenReturn(Timestamp.valueOf("2017-02-08 11:30:33.91"));

I tried to debug it and found that the call .thenReturn(Timestamp.valueOf("2017-02-08 11:29:31.3")) gives this exception:-

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Timestamp cannot be returned by toString()

This code works for one row but the next row it starts giving the above exception.

The calling function has this code-

while (rs != null && rs.next()) {
        resp = new ClassA();
        resp.setCreatedDt(rs.getTimestamp("CREATED_ON"));
}

Any help would be really appreciated.

Thanks Tausif

Upvotes: 2

Views: 981

Answers (1)

Tausif Shakeel
Tausif Shakeel

Reputation: 83

I was able to solve this issue by replacing the above code with this

thenReturn(Timestamp.valueOf("2017-02-06 14:16:39.78"),Timestamp.valueOf("2017-02-08 11:29:31.3"))

instead of chaining methods. Complete code:-

when(statement.getResultSet()).thenReturn(resultSet);
when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
when(resultSet.getString("HIST_ID")).thenReturn("").thenReturn("").thenReturn("").thenReturn("").thenReturn("");
when(resultSet.getTimestamp("CREATED_ON")).thenReturn(Timestamp.valueOf("2017-02-06 14:16:39.78"),Timestamp.valueOf("2017-02-08 11:29:31.3"), Timestamp.valueOf("2017-02-08 11:29:57.49"), Timestamp.valueOf("2017-02-08 11:30:13.47"), Timestamp.valueOf("2017-02-08 11:30:33.91"));

Though this solved my issue i am still not sure how this got solved by doing this.

Upvotes: 2

Related Questions