我正在为我的班级做Junit考试。我班的源代码是:
@Autowired
private LanguageRepository languageRepository;
@ApiOperation(value = "Languages", notes = "Get Languages.")
@CrossOrigin
@RequestMapping(method = RequestMethod.GET, path = Constants.REST_LANGUAGES)
public List<Language> getLanguages(HttpServletRequest request)
throws GlobalException, ServiceException, SoapException, RepositoryException {
LOG.info("Call Rest method: getLanguages");
List<Language> languages = languageRepository.getAllLanguages();
return languages;
}
LanguageRepository还有一个名为LanguageService的Autowired类。
文本的源代码是:
@Mock
private LanguageRepository languageRepository;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void exampleTest() throws GlobalException, ServiceException, SoapException, RepositoryException {
Language language = new Language("id", "name", "code");
List<Language> languageListGiven = new ArrayList<Language>();
languageListGiven.add(language);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(languageRepository.getAllLanguages()).thenReturn(languageListGiven);
// 2- act
LanguageController languageController = new LanguageController();
List<Language> languageListReturned = languageController.getLanguages(request);
// 3- assert
Assert.assertEquals(languageListGiven, languageListReturned);
}
但是当我调用存储库的方法时,我收到一个nullPointerException。
当我做“Mockito.when&#39;?
时,可以使用模拟工具来接收我想要的对象。”谢谢!
答案 0 :(得分:0)
您已为LanguageRepository
创建了一个模拟,但您尚未将其注入控制器。您需要在控制器中为languageRepository
创建一个setter方法,并在测试中使用它。
LanguageController languageController = new LanguageController();
languageController.setLanguageRepository(languageRepository);