2

I need to check if only specific http method is available for some url. For example, if there is a controller like this

@Controller
public class FooController {
    @RequestMapping(value = "bar", method = RequestMethod.GET)
    public void bar() {/*do something*/};
    ...
}

For controller test I use junit(4.10), spring-test(3.2.10) and easymock(3.1). If I write test like this

@Test
public void testBar() throws Exception {
    mockMvc.perform(post("bar").session(session))
    .andExpect(/*some application's default error response*/);
}

it will pass (although test calls post-method, not get-method).

So I'm looking for a proper way to make sure, that my rest resources are only avaiable by request methods specified in documentation. Two solutions came to my mind:

  • write tests with wrong request methods and somehow check resource is not available
  • add custom exception resolver to process org.springframework.web.HttpRequestMethodNotSupportedException: Request method '__' not supported and return same application default error response, but with https status 405 Method not allowed.

What would you suggest and how to check in controller test request method?

Thanks in advance.

1 Answer 1

3

You would need to check the status of all the request methods, you could do it using andExpect with status().isMethodNotAllowed() or status().isNotFound() depends on your needs:

Examples:

  • get: mockMvc.perform(get("bar").andExpect(status().isNotFound()) or mockMvc.perform(get("bar").andExpect(status().isMethodNotAllowed())

Do the same same for put, delete, ....

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.