第一个函数引发NullPointerException
,为什么会发生这种情况?第二个功能没有任何问题。
UrlShortenerTests.Java
//Test de redireccion si la url corta existe
@Test
public void thatRedirectToReturnsTemporaryRedirectIfKeyExists()
throws Exception {
when(shortURLRepository.findByKey("someKey")).thenReturn(new ShortURL("someKey", "http://example.com/", null, null, null,
null, 307, true, null, null));
mockMvc.perform(get("/l{id}", "someKey")).andDo(print())
.andExpect(status().isAccepted());
}
//Test de redireccion si la url corta no existe
@Test
public void thatRedirecToReturnsNotFoundIdIfKeyDoesNotExist()
throws Exception {
when(shortURLRepository.findByKey("someKey")).thenReturn(null);
mockMvc.perform(get("/l{id}", "someKey")).andDo(print())
.andExpect(status().isNotFound());
}
堆栈跟踪:
test.java.urlshortener2014.web.rest.UrlShortenerTests > thatRedirectToReturnsTemporaryRedirectIfKeyExists FAILED
org.springframework.web.util.NestedServletException at UrlShortenerTests.java:74
Caused by: java.lang.NullPointerException at UrlShortenerTests.java:74
最佳答案
查看代码后,您必须模拟UrlShortnenerOldBurgundy
中的所有注入。这包括在类WorkRepositorySponsor
的第58行中调用的UrlShortnenerOldBurgundy
并导致异常。只需添加UrlShortenerClass
:@Mock WorksRepositorySponsor worksRepositorySponsor;