WorksRepositorySponsor

WorksRepositorySponsor

第一个函数引发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;

09-11 17:48