anyString () è null invece di una stringa vuota

Sep 04 2020

Sto provando a testare il mio dao, tuttavia quando passo anyString (), nel mio dao esce come una stringa nulla e, di conseguenza, non restituisce il mio oggetto deriso che voglio

@InjectMocks
private Dao dao;

@Mock
@Qualifier("jdbcTemp")
private JdbcTemplate jdbcTemp;

@Test
public void testGetData() {
    List<MyObj> list = new ArrayList<>();
    MyObj myObj = new MyObj();
    myObj.setMethod("method val");
    list.add(myobj);

    Mockito.when(jdbcTemp.query(anyString(), Mockito.any(PreparedStatementSetter.class),
        Mockito.any(Dao.MyRowMapper.class))).thenReturn(list);

    List<MyObj> res = dao.getData(param1, param2); // this is empty, instead of having a value of 1

    Assertions.assertThat(res).isNotNull();
}

Il mio Dao

@Autowired
private String query;

@Autowired
private JdbcTemplate jdbcTemp;

public List<MyObj> getData(String arg1, String arg2) {
    List<MyObj> list = new ArrayList<MyObj>();

    try {
        // query below is null instead of empty string
        list.addAll(jdbcTemp.query(query, new PreparedStatementSetter() {
            public void setValues(PreparedStatement pstmt) throws SQLException {
                pstmt.setString(PARAM_ONE, arg1);
                pstmt.setString(PARAM_TWO, arg2);
            }
        }, new MyRowMapper()));
    } catch (Exception exp) {
    
}

return list;

}

Risposte

Campingenieur Sep 04 2020 at 14:55

Quindi, come hai detto correttamente anyString(), corrisponde solo a stringhe non nulle. e mentre passi queryal tuo metodo dovresti verificare che il tuo autowired querynon sia nullo. In alternativa potresti attenersi a any()o nullable(String.class)quale corrisponde a null. Poiché il tuo test non dipende dal queryvalore, puoi tranquillamente usarlo.

Tuttavia, poiché il codice non mostra come funziona l'iniezione, non è possibile per noi indagare ulteriormente sul problema. Se questo è necessario per te, aggiungi le parti di codice pertinenti.