我正在尝试测试控制器内部的方法。 如果我注释掉要测试的静态方法中的逻辑,则测试通过。
我不能评论这种逻辑,而只是想模拟它。现在,该模拟作品开始运作, 但出现以下新错误:
java.lang.AssertionError:内容类型未设置
但是我确实指出了内容类型。请批评我在做什么错。
@Test
public void testMethod() throws Exception{
// If I don't mock this, test will fail.
// If I don't mock this comment out logic in this method, test passes.
// If I mock this, test passes if I don't check for content type.
// I am using Power Mockito.
mockStatic(MyStaticClass.class);
doReturn("").when(MyStaticClass.class, "someMethod", any(Config.class), anyString());
//also tried this, works.
//when(MyStaticClass.someMethod(any(Config.class), anyString())).thenReturn("");
//as mentioned above this would work if I comment out logic in MyStaticClass.
mockMvc.perform(
get("/api/some/a/b/c/d").accept(
MediaType.APPLICATION_JSON))
.andExpect(status().isForbidden())
.andExpect(content().contentType("text/html")); // when I mock, I need to comment this out to get test to work.
}
// Controller
@RequestMapping(value = "/{a}/{b}/{c}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) // I do have content type
@ResponseBody
public MyResponse getSomething(
HttpServletRequest request, HttpServletResponse response,
@PathVariable String a, @PathVariable String b,
@PathVariable String c,
@RequestParam(value = "some", required = false) String some)
throws Exception {
// some logic
//static method being called
MyStaticClass.someMethod("sample", "sample2");
try {
MyResponse myPageResponse = new MyResponse(anotherStr, someStr); // it breaks here and throws that error msg. Doesn't reach return.
return MyResponse;
} catch (NullPointerException npe) {}
}
答案 0 :(得分:1)
这是一个没有正文的get请求,因此,理想情况下,使用contentType(“ text / html”)指定content-type标头可能不是正确的方法。 其次 您的请求中的内容类型标头必须与@consumes值匹配,它清楚地表明您希望发送text / html,但没有@consumes支持它。