繁体   English   中英

模拟静态方法时的内容类型错误

[英]Content type error when mocking static method

我正在尝试测试控制器内的方法。 如果我注释掉我正在测试的方法中调用的静态方法中的逻辑,则测试通过。

我不能评论那个逻辑,相反我只是想嘲笑它。 现在模拟工作,但我得到一个新的错误如下:

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) {}
}

这是一个 get 请求,它没有正文,因此理想情况下使用 contentType("text/html") 指定内容类型标头可能不是正确的方法。 其次,请求中的内容类型标头必须与 @consumes 值匹配,它清楚地表明您希望发送 text/html 但没有 @consumes 来支持这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM