i want to log in using spring mvc security to test the proj, but an exception was raised while runing the junit test method
the test method:
#Test
public void loginUser1Ok() throws Exception {
HttpSession session = mockMvc
.perform(
post("/j_spring_security_check").param("j_username",
"admin").param("j_password",
"secret"))
.andExpect(status().is(HttpStatus.FOUND.value()))
.andExpect(redirectedUrl("/")).andReturn().getRequest()
.getSession();
Assert.assertNotNull(session);
}
this exception was raised
java.lang.AssertionError: Response status expected:<302> but was:<200>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers$2.match(StatusResultMatchers.java:61)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)
at com.orange.weather.WebApplicationContextControllerTest.loginUser1Ok(WebApplicationContextControllerTest.java:157)
A response with status code 200 is not a redirect. I expect that
HttpSession session = mockMvc
.perform(
post("/j_spring_security_check").param("j_username",
"admin").param("j_password",
"secret"))
.andExpect(status().is(HttpStatus.FOUND.value()))
.getSession();
will work.
Related
How can I use Junit4 to test the thrown exception while using the exception mapper ?
To test a thrown exception, expected from the execution. Please use :
#Test(expected=<ExpectedException>.class)
public void testThrownException() {
// Your test code that throws the expected exception
}
The test would pass if your code throws the expected exception and fail for assertion failures and any other exception thrown by the code.
I am trying to mock the external call.
ResponseEntity<?> httpResponse = requestGateway.pushNotification(xtifyRequest);
requestGateway is an interface.
public interface RequestGateway
{
ResponseEntity<?> pushNotification(XtifyRequest xtifyRequest);
}
Below is the test method i am trying to do.
#Test
public void test()
{
ResponseEntity<?> r=new ResponseEntity<>(HttpStatus.ACCEPTED);
when(requestGateway.pushNotification(any(XtifyRequest.class))).thenReturn(r);
}
A compilation error is there in the above when statement,saying it as an invalid type.even thougg r is of type ResponseEntity.
Can anyone please help me to solve this issue ?
You can instead use the type-unsafe method
doReturn(r).when(requestGateway.pushNotification(any(XtifyRequest.class)));
Or you can remove the type info while mocking
ResponseEntity r=new ResponseEntity(HttpStatus.ACCEPTED);
when(requestGateway.pushNotification(any(XtifyRequest.class))).thenReturn(r);
I am adding JSONP support to a REST Service in SPRING4 + JDK 8 + STS 3.6.4
Versions:
Spring 4.1.6.RELEASE
My implementation is based on these links:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-jsonp
The REST service returns ResponseEntity or ResponseBody and use case is to return data in JSONP format.
Added a ControllerAdvice
#ControllerAdvice
public class JsonpCallbackAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpCallbackAdvice(){
super("Callback");
}
}
Here is the Controller of the REST Service
#Controller
public class AcctController {
...
#RequestMapping(value = "/act/{actNum}", method = RequestMethod.GET)
public ResponseEntity<Account> getAccount(#PathVariable("actNum") Integer accountNum) throws Exception {
...
return new ResponseEntity<account>();
}
Here is the relevant web application context configuration
...
<context:component-scan base-package="com.controllers" />
<bean name="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
...
The controller and ControllerAdvice are in same package.
When deployment of the project is initiated following exception is observed
Caused by: java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String
at org.springframework.context.annotation.AnnotationBeanNameGenerator.determineBeanNameFromAnnotation(AnnotationBeanNameGenerator.java:91)
at org.springframework.context.annotation.AnnotationBeanNameGenerator.generateBeanName(AnnotationBeanNameGenerator.java:69)
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:246)
at org.springframework.context.annotation.ComponentScanBeanDefinitionParser.parse(ComponentScanBeanDefinitionParser.java:84)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:74)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1427)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1417)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:174)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:144)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:100)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:510)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
This exception was not happening before the ControllerAdvice was added.
Also, it does not happens when #ControllerAdvice annotation is removed
or
the component scan excludes scanning package of the ControllerAdvice class
I tried with Spring version 4.2.0.RC1, and the exception still happens.
Kindly help with resolution of this exception, since not much help is available online.
It seems like a bug in SPRING 4, however am not sure.
I need to send a stub response over http to a requesting client from Jetty. It works when I run the Junit test independently, implies, I get the correct XML response .. but it fails when I run the same thing from maven. The error I see is "java.net.SocketException: Unexpected end of file from server". I have tried everything! Please help!
Here's my code -
Junit (when run as a Junit test - it works)
public class MyTest {
#Test
public void testGetOpenLots() throws Exception {
// create fixture
MyService fixture = new MyService();
// create jetty server instance
Server server = new Server(8080);
// set a handler
server.setHandler(new HelloHandler());
// set shutdown conditions
// server.setStopAtShutdown(true);
// start server
server.start();
// invoke operation
MyResponse result = fixture.getWeather(someDummyRequest);
assertNotNull(result);
}
}
Somewhere down the line, inside getWeather(), I create a URL object and pass the URL http://localhost:8080 to it and send the request to that URL. At this point, I expect that the HelloHandler's handle method will get invoked and will write this dummy XML response to stream and getWeather() method will receive the response.
Here's the handler:
public class HelloHandler extends AbstractHandler {
public void handle(String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("application/xml;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("<result>a simple response</result>");
}
}
When I run the same thing from maven, it throws the error mentioned above. What am I doing wrong?
Instead of implementing your own jetty handler you can try Jadler (http://jadler.net), an http stubbing/mocking library I've been working on for a while.
I'm attempting to bind json to the model with #RequestBody.
We are validating our model using JSR303.
Here is the method signature
#RequestMapping(value = "/editCampaign.do", method = { RequestMethod.POST })
public ModelAndView editCampaign(#RequestBody #Valid Campaign campaign,
HttpServletRequest request)
If a piece of required information is missing a MethodArgumentNotValidException is thrown (as I read in the docs). I really want to be able to return this information back to the view so I can show the user that they've not filled out a required field. Once the exception is thrown, it seems as though it's too late. Obviously, I don't have a bindingresult to inspect.
Am I incorrectly using the framework? How do I set up this scenario correctly?
First Of all I recommend you to return String instead ModelAndView especially in Spring 3.1.
If you want to catch Exception from #ResponseBody annotated method, I recommend you to use the following:
1) Catch the exception with #ExceptionHandler annotation:
#ExceptionHandler(MethodArgumentNotValidException.class)
public String handleMyException(MethodArgumentNotValidException exception) {
return "redirect:errorMessage?error="+exception.getMessage());
}
and then Redirect to view annotated with #ResponseBody argument
#RequestMapping(value="/errorMessage", method=RequestMethod.GET)
#Responsebody
public String handleMyExceptionOnRedirect(#RequestParamter("error") String error) {
return error;
}