-1

MyCode

 @AutoConfigureMockMvc
    public class NewsletterTest {

      @Autowired
      private MockMvc mockMvc;


      @MockBean
      private NewsletterService service;

      @Test
      public void deleteNewsletterShouldDelete() throws Exception {

        this.mockMvc.perform(MockMvcRequestBuilders
                .delete("/delete-newsletter/11")
                .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());

        verify(service, times(1)).deleteNewsletter(11L);

    }

The error:

java.lang.NullPointerException
    at controller.NewsletterTest.deleteNewsletterShouldDelete(NewsletterTest.java:33)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at 

In my spring boot test case, I am using @AutoConfigureMockMvc and @MockBean to test a delete method in my newsletter controller. However, I am encountering a java.lang.NullPointerException at line 33 of my test case. I want to understand the cause of this error.

  • Hello! This is quite hard to know what your issue might be as we don't have the line number. But I guess the line with `this.mockMvc.perform` throws the NPE? – A Le Dref Feb 03 '23 at 10:00
  • Yes, Line 33 is this.mockMvc.perform, it throws the NPE because mockMvc is null but i don't know why? – Mark likes Quark Feb 03 '23 at 10:04

1 Answers1

1

I see that your only anontation on your test is @AutoConfigureMockMvc. However that is not sufficient to start a Spring Boot application context.

As you are targeting a controller you should at least add @WebMvcTest(controllers=[controller_class_here].

This will setup everything and maybe resolve your NullPointerException.

Also doing so you won't need the @AutoconfigureMockMvc annotation

A Le Dref
  • 422
  • 3
  • 7