NullPointerException in my unit test

The first function throws NullPointerException, why does this happen? The second function doesn't have any problems.

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());
}

Stack trace:

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

Upvotes: 0

Views: 1740

Answers (1)

After reviewing your code, you must mock all the injections in UrlShortnenerOldBurgundy. That includes WorkRepositorySponsor which is invoked in line 58 of your class UrlShortnenerOldBurgundy and causes the exception. Just add in UrlShortenerClass:

@Mock WorksRepositorySponsor worksRepositorySponsor;

Upvotes: 1

Related Questions