Mockmvc控制器引发NullPointerException

时间:2018-10-28 19:52:30

标签: unit-testing mockito

也许有人可以告诉我为什么在测试Controller时总是得到NullPointerException。 它告诉我NullPointerException发生在这里:

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

这是我的代码:

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

我想要实现的是在不加载整个ApplicationContext的情况下测试控制器。


为了避免NullPointerException,我不得不对其进行调整:

引入了一个新类:

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

}

在我的设置方法中:

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

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

唯一的问题是现在出现404错误。

我是否必须将index.html放入

/src/test/resources

也是吗?

enter image description here

0 个答案:

没有答案