使用SpringFramework Test和Mockito对HttpServletResponse响应进行Nullpointer

时间:2015-11-05 23:44:34

标签: spring-mvc junit mockito spring-test

我正在使用独立设置测试我的Spring @RestController,并使用mockito模拟一些自动连接的bean,到目前为止我的所有测试都已成功,直到我尝试测试这个restservice:

@RequestMapping(value = "/some/{someId}/other/someagain", method = RequestMethod.POST)
public FileSystemResource downloadInvoiceQuery(@PathVariable Long someId,
        @RequestBody SomeClass request, HttpServletResponse response) {
.
.
.
mockedBean.method("object1","object2");
response.setHeader("some headers");
}

使用此测试:

when(mockedBean.method(any(), any())).thenReturn(null);

mockMvc.perform(MockMvcRequestBuilders.post("/some/{someId}/other/someagain", 1L)
.contentType(MediaType.APPLICATION_JSON).content("{}")).andExpect(MockMvcResultMatchers.status().isOk());

当通过Controller中的HttpServletResponse对象调用setHeaders方法时,我得到一个Nullpointer。我无法弄清楚如何注入或传递响应对象以避免空指针。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

测试spring mvc控制器时,我总是使用MockMvc

点击此处查看示例: How to test a spring controller method by using MockMvc?

可在此处找到文档: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#spring-mvc-test-framework

以下是使用独立设置的文档中的示例:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("test-servlet-context.xml")
public class ExampleTests {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void getAccount() throws Exception {
        this.mockMvc.perform(get("/accounts/1").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
            .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$.name").value("Lee"));
    }

}