0

in my class namedJdbcTemplate is being used twice in single function to get different result. but mocking it only gives one result. how to prepare test case for it ?

my class:

public void Getsomething(){

Result1 = namedJdbcTemplate.queryForObject(
            "SomeSQLString1", params, String.class);

Result2 = namedJdbcTemplate.queryForObject(
    "SomeSQLString2", params, String.class);        

Test Class:

@Test
public void getNewRecordsTest2(){

Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
            Mockito.any(String.class))).thenReturn(Result1);

Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
        Mockito.any(String.class))).thenReturn(Result2);

    /**calling actual*/
    SomeClass.Getsomething();

}

i tried to call it twice but it will hold only one result.

mockito.doreturn fails to give any result and calls real method inside function, provide null result

    @Test
public void getNewRecordsTest2(){

Mockito.doReturn(Result1).when(namedJdbcTemplate).queryForObject("SomeSQLString1", params, String.class);

Mockito.doReturn(Result2).when(namedJdbcTemplate).queryForObject("SomeSQLString1", params, String.class);

    /**calling actual*/
    SomeClass.Getsomething();

}
Akhil Kumar
  • 140
  • 1
  • 9
  • 1
    Does this answer your question? [How to tell a Mockito mock object to return something different the next time it is called?](https://stackoverflow.com/questions/4216569/how-to-tell-a-mockito-mock-object-to-return-something-different-the-next-time-it) – Amongalen Feb 20 '20 at 09:09
  • I'm thinking about the most rated answer from the duplicate, not the accepted one. – Amongalen Feb 20 '20 at 09:11

2 Answers2

0

Here is a nice tutorial about this

Wiciaq123
  • 486
  • 4
  • 13
0

i got the answer :

Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
        Mockito.any(String.class))).thenReturn(Result1, Result2);

this will give two different result Result1 and Result2 with a single mock

Akhil Kumar
  • 140
  • 1
  • 9