简体   繁体   中英

anyString() is null instead of empty string

I'm trying to test my dao, however when I pass anyString(), in my dao it's coming out as a null string and as a result, it's not returning my mocked object that I want

@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();
}

My 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;

}

So as you mentioned correctly anyString() does only match for non-null Strings. and as you pass query into your method you should verify, that your autowired query is not null. As an alternative you could stick to any() or nullable(String.class) which matches for null. Since your test does not depend on the query value you can safely use this.

However as your code does not show how your Injection works it is not possible for us to investigate your problem further. If this is necessary for you please add the relevant code parts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM