anyString ()은 빈 문자열 대신 null입니다.

Sep 04 2020

내 dao를 테스트하려고하는데 anyString ()을 전달하면 dao에서 null 문자열로 나오고 결과적으로 원하는 모의 객체를 반환하지 않습니다.

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

}

답변

Campingenieur Sep 04 2020 at 14:55

따라서 올바르게 언급했듯이 anyString()null이 아닌 문자열에만 일치합니다. 그리고 당신이 query당신의 방법으로 전달할 때 당신은 autowired query가 null이 아닌지 확인해야합니다 . 대안으로 당신은 고착 any()하거나 nullable(String.class)null과 일치하는 것이 있습니다. 테스트가 query값에 의존하지 않기 때문에 안전하게 사용할 수 있습니다.

그러나 코드에 인젝션의 작동 방식이 표시되지 않으므로 문제를 더 자세히 조사 할 수 없습니다. 이것이 필요한 경우 관련 코드 부분을 추가하십시오.