【发布时间】:2014-12-04 19:37:15
【问题描述】:
我有一个小型 Spring MVC 项目。我正在为它编写 MockMvc 测试。它们中的大多数都可以工作,但是这个(我尝试过的第一个使用纯 JSON 正文的)给我带来了麻烦。我不断从 Spring 内部得到 NullPointerException。我尝试通过它进行调试,但最终用完了附加的 Spring 源代码而没有更接近答案。
我的 JSON 块是从实时用户测试中捕获的,效果很好。但是在测试中,它会抛出 NPE。如果我将 JSON 块修改为格式错误(IE,在某处添加一个额外的逗号),那么它会按预期抛出 400 Bad Request。去掉多余的逗号,回到 NPE。使块无效(IE,使我的域对象中标记为@NotNull 的字段为空)不会给出预期的 400 错误请求。它只保留在 NPE 中。
到目前为止,我所有的其他测试都是针对只使用查询字符串参数的控制器,并且运行良好。另外,我有一个由于我们客户方面的浏览器限制,必须将其 JSON 嵌入到 POST 参数(IE,“json =”{blah:blah}“)中,我将其取出并手动解析。这也很好.
控制器:
@RestController
public class SaveController {
@Autowired
private MyDao myDao;
@RequestMapping(value = "/path/to/controller", method = RequestMethod.POST)
@PreAuthorize("hasAnyRole('myRole', 'myAdminRole')")
public void updateThing(@Valid @RequestBody MyThing myThing) throws IOException {
myDao.updateMyThing(myThing);
}
}
基础测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {TestDataAccessConfiguration.class, TestApplicationConfiguration.class})
public abstract class AbstractSpringTestCase {
@Autowired
protected WebApplicationContext wac;
protected MockMvc mockMvc;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
MockitoAnnotations.initMocks(this);
}
}
测试:
public class SaveControllerTest extends AbstractSpringTestCase {
@Mock
private MyDao myDao;
@InjectMocks
@Autowired
private SaveController classUnderTest;
private static final JSON = "<a big JSON string captured from (working) production>";
@Test
public void testHappyPath() throws Exception {
mockMvc.perform(post("/path/to/controller")
.contentType(MediaType.APPLICATION_JSON)
.content(JSON))
.andExpect(status().isOk());
}
}
堆栈跟踪:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:170)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:137)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:145)
at SaveControllerTest.testHappyPath(SaveControllerTest.java)
【问题讨论】:
-
请发布堆栈跟踪的其余部分。
标签: java json spring spring-mvc