我有一个类,它的成员通过构造函数注入,其他成员通过设置器注入。我似乎无法让 Mockito 注入二传手。构造函数注入被模拟得很好,但设置器返回为空。当我将 setter-ed 成员翻转到构造函数注入时,一切都很好。这是原始生产代码:
@Autowired
private BetRepository betRepository;
public void setBetRepository(BetRepository betRepository) {
this.betRepository = betRepository;
}
public TournamentScoringCache(TournamentScoringCacheInitializer cacheInitializer,
ScoringEngineInitializer scoringEngineInitializer) {
tournamentUserStates = cacheInitializer.initCache();
scoringEngines = scoringEngineInitializer.initEngines();
}
public <T extends SideScore> void updateGameScore(Long tournamentId, Long gameId, MatchScore<T> score) {
Map<Long, UserTournamentState> userStates = tournamentUserStates.get(tournamentId);
ScoringEngine<?> scoringEngine = scoringEngines.get(tournamentId);
List<Bet> bets = betRepository.getBetsByGameId(gameId); //HERE IS WHERE I GET THE NPE
....
}
测试代码:
@Mock
BetRepository betRepository;
@Mock
TournamentScoringCacheInitializer cacheInitializer;
@Mock
ScoringEngineInitializer engineInitializer;
@InjectMocks
private TournamentScoringCacheAndDB tournamentScoringCache;
@Test
public void testUpdateGameScore() {
....
when(cacheInitializer.initCache()).thenReturn(utss);
when(betRepository.getBetsByGameId(1L)).thenReturn(createBets());
when(engineInitializer.initEngines()).thenReturn(createEngines());
when(engine.getBetScore(bet1, score)).thenReturn(betScore);
when(engine.getBetScore(bet2, score)).thenReturn(betScore2);
tournamentScoringCache.updateGameScore(tournamentId, gameId, score);
....
}
有任何想法吗?
谢谢!