How can I test my controller for throwing an exception in Kotlin? - spring

So I have a controller with one GET method. I need to test it. When I write in URL request with incorrect iso code of the country, it throws me back a custom exception. So how can I test it?
So here 'UA' is incorrect argument
#Test
fun check_for_incorrect_iso_code() {
mockMvc.perform(get("/countries/UA"))
.andDo(print())
.andExpect(status().is4xxClientError)
}
Test is working, but I need to extend it and check if it throws my custom exception - 'InvalidIsoCodeException' for example.
Thanks for the answer.

Your Java code is throwing an InvalidIsoCodeException but your server/controller cannot throw exceptions. Instead it sends back an HTTP response to the client. The InvalidIsoCodeException is mapped by Spring to a specific response. You're already checking the status of the response with .andExpect(status().is4xxClientError()). You can also verify the body of the response if you want to be more specific.
If you want to test for the exception then you have to test your controller like a normal Java class without MockMVC.

Related

Spring webflow prevent GET method in transition

I am using spring webflow 2.3.1.RELEASE in my project.
The customer's security team raised and issue witch is "It is possible to change the http method from POST to GET and the application accepts the change and continues working."
So I need to prevent this change and make my transitions accept only POST method. Or throw exception if I get any request parameter other than execution in the url.
How can I do this?
You could create your own FlowExecutionListener and throw an exception when the request method is different than POST and/or when request parameters are present.
see the documentation here and API here
I solved the problem using interceptors of the FlowHandlerMapping.
I've created a class and named it MethodInterceptor, implementend org.springframework.web.context.request.WebRequestInterceptor.
in the "public void preHandle(WebRequest request) throws Exception" method, I checked the request method, if it was get, I checked the request parameters to be either empty or contain only the execution parameter. If the condition didn't meet, I threw an exception.

Configuring Spring WebSecurityConfigurerAdapter to use exception handler

Spring Boot here. I just read this excellent Baeldung article on Spring Security and implementing basic auth with it. I'm interested in implementing it for a simple REST service (so no UI/webapp) that I need to build.
I'm particularly interested in the BasicAuthenticationEntryPoint impl. In this impl's commence override, the author:
Adds a WWW-Authenticate header to the response; and
Sets the HTTP status code on the response; and
Writes the actual response entity directly to the response; and
Sets the name of the realm
I want to follow this author's example to implement basic auth for my app, but I already have a perfectly functioning ResponseEntityExceptionHandler working for my app:
#ControllerAdvice
public class MyAppExceptionMapper extends ResponseEntityExceptionHandler {
#ExceptionHandler(IllegalArgumentException.class)
#ResponseBody
public ResponseEntity<ErrorResponse> handleIllegalArgumentExeption(IllegalArgumentException iaEx) {
return new ResponseEntity<ErrorResponse>(buildErrorResponse(iaEx,
iaEx.message,
"Please check your request and make sure it contains a valid entity/body."),
HttpStatus.BAD_REQUEST);
}
// other exceptions handled down here, etc.
// TODO: Handle Spring Security-related auth exceptions as well!
}
Is there any way to tie Spring Security and Basic Auth fails into my existing/working ResponseEntityExceptionHandler?
Ideally there's a way to tie my WebSecurityConfigurerAdapter impl into the exception handler such that failed authentication or authorization attempts throw exceptions that are then caught by my exception handler.
My motivation for doing this would be so that my exception handler is the central location for managing and configuring the HTTP response when any exception occurs, whether its auth-related or not.
Is this possible to do, if so, how? And if it is possible, would I need to still add that WWW-Authenticate to the response in my exception handler (why/why not)? Thanks in advance!
I don't think that this is possible. Spring security is applied as a ServletFilter, way before the request ever reaches any #Controller annotated class - thus exceptions thrown by Spring Security cannot be caught by an exception handler (annotated with #ControllerAdvice).
Having had a similar problem, I ended up using a custom org.springframework.security.web.AuthenticationEntryPoint which sends an error, which in turn is forwarded to a custom org.springframework.boot.autoconfigure.web.ErrorController

How can I see the json coming from the client when using Spring-MVC?

A client software is trying to access my Spring-MVC rest server, but it's getting a 400 (Bad Request) response every time. I know my server is fine (it's in use by many other clients), but I cannot debug the client application, so I cannot see what it is sending.
Is there a way for me to see what JSON I am receiving before Spring tries to convert it to an entity and fails? It's okay if I can only do this at debug time, I just need to be able to give support to this application's creators.
Just in case, here is the spring-mvc controller method:
#Named
#RequestMapping(value = "/taskmanager/task")
public class TaskManagerTaskRest {
#RequestMapping(value = "", method = RequestMethod.POST)
#ResponseBody
public void createTask(#RequestBody Task task, HttpServletRequest request,
HttpServletResponse response) throws CalabacinException {
// This code never gets executed because the Task json is invalid, but I don't know how I could see it.
...
...
}
}
Try to use Fiddler. It will help you to catch HTTP requests/responses. You will be able to see your JSON.
You can create and use a AbstractRequestLoggingFilter filter implementation and conditionally log the relevant parts of the request. You should use ContentCachingRequestWrapper to wrap the request.

How to send the send status code as response for 404 instead of 404.jsp as a html reponse in spring?

I created web application in spring and handled exception mappings for 404 and 500.If system doesn't find any resources for requested URL it redirects into custom 404.jsp instead of regular 404 page.Everything works fine till have decided to add a webservice in my app.I have included one more controller as a webservice there is no view for this controller and this needs to be invoke through curl command.
User may get into change the curl script.If they changed the URL it should show 404 status code.But it returns the custom 404.jsp as a html response instead of status code.Because dispatcher servlet will takes all urls with /*.
How I can solve this issue?
Please share your suggestions.
Spring 3.2 introduced the #ControllerAdvice, and as mentioned in the documentation:
It is typically used to define #ExceptionHandler
That means you can use the #ControllerAdvice to assist your #Controller like the following:
#ControllerAdvice
class GlobalControllerExceptionHandler {
#ResponseStatus(HttpStatus.NOT_FOUND) // 404
#ExceptionHandler(Exception.class)
public void handleNoTFound() {
// Nothing to do
}
}
For further details please refer to this tutorial and this answer.

Spring mvc controller test + Json response error

I have in my spring mvc test controller:
#Test
public void consultaPorIdJson() throws Exception{
mockMvc.perform(get("/timesheet/consultaporidjson/{id}", 1L))
.andExpect(status().isOk())
.andExpect(content().contentType(TestSupport.APPLICATION_JSON_UTF8))
.andExpect(content().string("{\"id\":1,\"latitude\":\"30.448660206791608\",\"longitude\":\"-44.29684999999995\"}"));
When I trying to run my test I get an error:
java.lang.IllegalStateException: Cannot set error status - response is already committed
I think that is about 2k (I think) of response, but I don't know what must I do to fix it :-(
Does the url works outside of your test? I doubt it does not work as the error suggests you have issue in your implementation where the code is trying to change the status when something is already written in the response.

Resources