0

maybe someone can tell me why I always get NullPointerException when testing my Controller. It tells me that the NullPointerException happens here:

mvc.perform(get("/passwordaenderung"))

Here is my code:

public class LagerstandortControllerTest {
    @InjectMocks
    private PasswordChange passwordChange;
    // add @Mock annotated members for all dependencies used by the controller here
    private MockMvc mvc;

// add your tests here using mvc.perform()
    @Test
    public void getHealthStatus() throws Exception {
         mvc.perform(get("/passwordaenderung"))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.status", is("OK")));
    }

@Before
public void createControllerWithMocks() {
  MockitoAnnotations.initMocks(this);
  MockMvcBuilders.standaloneSetup(new PasswordChange()).build();
}
}

What I want to achieve is to test my controller without loading the whole ApplicationContext.


I had to adapt it in order to avoid a NullPointerException:

Introduced a new class:

public class StandaloneMvcTestViewResolver extends InternalResourceViewResolver {

public StandaloneMvcTestViewResolver() {
    super();
}

@Override
protected AbstractUrlBasedView buildView(final String viewName) throws Exception {
    final InternalResourceView view = (InternalResourceView) super.buildView(viewName);
    // prevent checking for circular view paths
    view.setPreventDispatchLoop(false);
    return view;
}

}

And in my setup method:

@Before
public void setUp() {
    final MainController controller = new MainController();

    mvc = MockMvcBuilders.standaloneSetup(controller)
                    .setViewResolvers(new StandaloneMvcTestViewResolver())
                    .build();
}

The only problem is now that I get a 404 error.

Do I have to put my index.html in

/src/test/resources

too?

enter image description here

Bernd
  • 593
  • 2
  • 8
  • 31
  • Well, you never initialize mvc anywhere. So it's null. You create a MockMvc instance in createControllerWithMocks, but you don't do anything with it. – JB Nizet Oct 28 '18 at 20:10
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – JB Nizet Oct 28 '18 at 20:11
  • Thank you very much! I was able to solve parts of my problems - I edited my question, since I get another error now: 404. Do I have to put my login.html under src/test/resources, too? – Bernd Oct 28 '18 at 20:45

0 Answers0