Reputation: 1
I'm trying to test a class in a Spring project. I have the following methods
public List<Range> getRanges() {
return getJdbcTemplate().query(RANGE_SQL, new RangeMapper());
}
public List<Score> getScores() {
return getJdbcTemplate().query(SCORE_SQL, new ScoreMapper());
}
public Map<String, Object> getData() {
//other code
final List<Range> ranges = getRanges();
final List<Score> scores = getScores();
}
In test case for getData()
-
when(jdbcTemplate.query(any(String.class), any(RangeMapper.class))).thenReturn(rangeList);
when(jdbcTemplate.query(any(String.class), any(ScoreMapper.class))).thenReturn(scoresList);
when I run the test for getData
, it's failing with ClassCastException
stating "Score cannot be cast to Range". When i debug and see, getRanges()
in getData()
is returning scoresList
. Why is this happening and how to solve this?
Upvotes: 0
Views: 315
Reputation: 2154
I would recommend to mock the getRanges()
and the getScores()
methods instead.
when(theClass.getScores()).thenReturn(scoresList);
when(theClass.getRanges()).thenReturn(rangesList);
If you need to do it your way you should specify the string to get the right result:
when(jdbcTemplate.query(SCORE_SQL, any(ScoreMapper.class))).thenReturn(scoresList);
when(jdbcTemplate.query(RANGE_SQL, any(RangeMapper.class))).thenReturn(rangesList);
The specification any(String.class)
is the breaking point here. In your case you've got the problem that you haven't specified in which case it returns the right thing.
So if you specify the given String
it should return the right List
Upvotes: 1