简体   繁体   中英

Content type error when mocking static method

I am trying to test a method inside a controller. The test passes if I comment out logic inside a static method that is called in the method I am testing.

I can't be commenting out that logic and instead I just want to mock it. Now the mock works, but I get a new error as follows:

java.lang.AssertionError: Content type not set

But I do have the content type indicated. Please advie what I am doing wrong.

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

This is a get request it doesn't have a body hence Ideally specifying content-type header using contentType("text/html") may not be a right approach. Secondly your content-type header in request must match with the @consumes value, it clearly state that you are expecting to send text/html but there is no @consumes to support that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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