I am having a problem with the following line of code:
OrderForm of = (OrderForm)form;
form is ActionForm and OrderForm is a class that extends ActionForm.
But I am trying to test this method and I don't how to do this.
For the reference, this is the method:
OrderForm of = (OrderForm)form;
System.out.println(Integer.parseInt(getPublisherId(req)));
of.setPublisherId( Integer.parseInt(getPublisherId(req)) );
AdvertiserManager am = new AdvertiserManager();
OrderManager om = new OrderManager();
of = om.getOrder(of, Locale.getDefault());
//If no valid campaign was found the id of 'of' is 0. So if id = 0 return 404 status.
if (of.getId() == 0) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return null;
}
METHOD signature:
public ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse response)
Exception:
java.lang.ClassCastException: org.apache.struts.action.ActionForm$$EnhancerByMockitoWithCGLIB$$3538880f cannot be cast to xxx.forms.orders.OrderForm
at xxx.IPOrderApiAction.performAction(IPOrderApiAction.java:82)
at xxx.IPOrderApiActionTest.testGetOrderApiCallNotExistingCampaignId(IPOrderApiActionTest.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Test:
private IPOrderApiAction spy;
#Test
public void testGetOrderApiCallNotExistingCampaignId() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
ActionMapping mapping = mock(ActionMapping.class);
ActionForm form = mock(ActionForm.class);
OrderForm of = mock(OrderForm.class);
Map<String,Object> map = new HashMap<String,Object>();
map.put("id", "1261");
spy = Mockito.spy(new IPOrderApiAction());
Mockito.doReturn("1").when((IPAuthenticatedAction)spy).getPublisherId(request);
request.setParameters(map);
when(mapping.getParameter()).thenReturn("getOrder");
spy.performAction(mapping,form, request, response);
assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
}
It's struts 1.1
You're not passing an instance of OrderForm to your method, but an instance of ActionForm:
ActionForm form = mock(ActionForm.class);
...
spy.performAction(mapping,form, request, response);
For the cast to succeed, the form must be an instance of OrderForm, so you need
ActionForm form = mock(OrderForm.class);
...
spy.performAction(mapping, form, request, response);
Related
Getting NullPointerException while running a JUnit test. I have already mocked the ClientHttpResponse class. Not sure what else I am missing.
Error:
java.lang.NullPointerException
at org.springframework.web.client.DefaultResponseErrorHandler.hasError(DefaultResponseErrorHandler.java:75)
at org.springframework.web.client.DefaultResponseErrorHandler.hasError(DefaultResponseErrorHandler.java:50)
at com.tss.payhub.template.rest.client.CustomResponseErrorHandler.hasError(CustomResponseErrorHandler.java:20)
at com.tss.payhub.template.rest.client.test.CustomResponseErrorHandlerTest.testHasError(CustomResponseErrorHandlerTest.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
CustomResponseErrorHandlerTest.java
public class CustomResponseErrorHandlerTest {
#Mock
ClientHttpResponse response = Mockito.mock(ClientHttpResponse.class);
#Test
public void testHasError() throws IOException {
CustomResponseErrorHandler instance = new CustomResponseErrorHandler();
boolean blnVal = instance.hasError(response);
assertTrue(blnVal);
}
}
CustomResponseErrorHandler.java (Class Under Test)
#Component
public class CustomResponseErrorHandler implements ResponseErrorHandler {
private ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();
public boolean hasError(ClientHttpResponse response) throws IOException {
return errorHandler.hasError(response);
}
}
Try adding #RunWith(EasyMockRunner.class) to your test class:
#RunWith(EasyMockRunner.class)
public class CustomResponseErrorHandlerTest {
I'm very new to Mockito and JUnit. I'm working on creating a test case for "forgot password"-workflow. Below is the code for the controller and the test. The test case fails because of a NullPointerException. I added the stacktrace below. Could anyone help me to fix the code? Thanks!
#RequestMapping(value = "/user/public/forgotPassword", method = RequestMethod.POST)
public ModelAndView sendforgetPasswordLink(#ModelAttribute ForgetPasswordBean forgetPasswordBean,BindingResult result, HttpSession session) {
BreadCrumbBuilder.addLinktoBreadCrumb(session, new Link(Constants.FORGET_PASSWORD_TITLE, "/user/public/forgotPassword", Constants.GROUP_USER, 0));
Map<String, String> breadCrumbs = HomePageController.setupInitialBreadCrumbs(session);
breadCrumbs.put(Constants.FORGET_PASSWORD_TITLE, "/user/public/forgotPassword");
session.setAttribute(SessionAttributes.BREAD_CRUMBS,breadCrumbs);
ModelAndView mav = new ModelAndView();
mav.addObject("displayTitle", Constants.FORGET_PASSWORD_TITLE);
PublicUser user = publicUserService.findPublicUserByEmail(forgetPasswordBean.getEmail().toLowerCase());
if(user == null) {
result.reject("email", "An account does not exist for this email.");
mav.setViewName("publicuser/forgetPassword.jsp");
return mav;
}
String randomId = java.util.UUID.randomUUID().toString();
user.setTempId(randomId);
mailService.sendForgetPasswordLink(user);
publicUserService.savePublicUser(user);
String msg = "Password reset instructions have been sent to your email.";
mav.addObject("msg", msg);
mav.setViewName("message.jsp");
return mav;
}
This is test I created so far
#Test
public void TestForgetPasswordForNoUserFound() throws Exception {
final String input_email = "abc#test.com";
ForgetPasswordBean forgetPasswordBean = new ForgetPasswordBean();
forgetPasswordBean.setEmail(input_email);
when(mockPublicUserService.findPublicUserByEmail(input_email)).thenReturn(null);
final ModelAndView modelAndView = controller.sendforgetPasswordLink(forgetPasswordBean, mockBindingResult, mockHttpSession);
verify(mockBindingResult).reject("email", "An account does not exist for this email.");
assertEquals("publicuser/forgetPassword.jsp", modelAndView.getViewName());
assertModelAttributeValue(modelAndView, "displayTitle", Constants.FORGET_PASSWORD_TITLE);
}
The trace starts here
java.lang.NullPointerException
at gov.hhs.cdelr.web.PublicUserControllerTest.TestForgetPasswordForNoUserFound(PublicUserControllerTest.java:105)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Line 410 is this line:
result.reject("email", "An account does not exist for this email.");
As the code of your test does not seem to be complete, i assume you forgot to initialize mockBindingResult for this testcase.
Sadly i can't tell you more as i do not see a setUp method nor the rest of the test class.
A setup method could be helpful, as it will run before every test, in there you should initialize your mockBindingResult.
#Before
public void setUp() {
// Do Stuff before every test
}
I have this class JerseySpringSuiteTest.java:
#RunWith(Suite.class)
#Suite.SuiteClasses({ ProductTest.class })
public class JerseySpringSuiteTest {
public static JerseyTest jerseyTest;
#BeforeClass
public static void init() {
jerseyTest = new JerseyTest(new WebAppDescriptor.Builder("com.product.resource")
.contextParam("contextConfigLocation", "classpath:applicationContext.xml").servletClass(SpringServlet.class)
.contextListenerClass(ContextLoaderListener.class).requestListenerClass(RequestContextListener.class).build()) {
};
}
}
and ProductTest.java:
public class ProductTest{
#Before
public void before() throws Exception {
JerseySpringSuiteTest.jerseyTest.setUp();
ExecutorService productExecutorService = ContextLoaderListener.getCurrentWebApplicationContext().getBean(
"productExecutorService", ExecutorService.class);
Assert.assertNotNull(productExecutorService);
}
#Test
public void testNoAction() {
WebResource webResource = JerseySpringSuiteTest.jerseyTest.resource();
String responseMsg = webResource.path("product/").get(String.class);
Assert.assertEquals("No Action Specified", responseMsg);
}
#Test
public void testGetProducts() throws URISyntaxException {
WebResource webResource = JerseySpringSuiteTest.jerseyTest.resource().path(
"Products/rest/product/getProducts/1/productName/01-01-2013/");
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
Assert.assertEquals(200, response.getStatus());
}
}
and Product.java:
#Component
#Path("/product")
public class Product{
#Autowired
private ProductService productService;
#GET
#Produces(MediaType.APPLICATION_JSON)
public Object noAction() {
return "No Action Specified";
}
#GET
#Path("/getProducts/{companyID}/{companyName}/{date}")
#Produces(MediaType.APPLICATION_JSON)
public Object getProducts(#PathParam("companyID") final int companyID,
#PathParam("date") final String date, #PathParam("companyName") final String companyName)
throws IOException {
return productService.getProducts(companyID, companyName, date);
}
}
When I execute it I see:
java.lang.AssertionError: expected:<200> but was:<404>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:743)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:555)
at org.junit.Assert.assertEquals(Assert.java:542)
at com.product.resource.MonitoringEngineResourceTest.testGetProducts(ProductTest.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runners.Suite.runChild(Suite.java:127)
at org.junit.runners.Suite.runChild(Suite.java:26)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
I am able to get data when I ping URL in browser.
Could some one please help me to get response status as 200 and JSON object?
NOTE: I am using jersey 1.17.1 version and grizzly2 container.
According to your noAction unit test, the correct URL seems to be:
webResource.path("product/")
This is also confirmed by your actual service class:
#Path("/product")
public class Product {
//...
}
This means that you need to change your other test to use the same path.
Also, it is companyName, not productName as per your service class.
#Test
public void testGetProducts() throws URISyntaxException {
WebResource webResource = JerseySpringSuiteTest.jerseyTest.resource();
ClientResponse response =
webResource.path("product/getProducts/1/companyName/01-01-2013/")
.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
Assert.assertEquals(200, response.getStatus());
}
One possible reason that it works in a browser is that your server (Tomcat, Jetty, etc.) is configured to add the common URL prefix Products/rest to all paths. This server is not in the picture when you execute unit tests.
I have got a junit test which performs a request using Spring MockMvc.
private MockMvc mvc;
#Before
public void setUp() {
mvc = MockMvcBuilders.standaloneSetup(new LoginController())
.addFilter(new AnonymousAuthenticationFilter("anonymous"))
.addFilter(new SecurityContextHolderAwareRequestFilter())
.addFilter(new XssValidationFilter()).build();
SecurityContextHolder.getContext().setAuthentication(null);
}
#Test
public void test() throws Exception {
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/login.htm")
.param(USER, "admin").param(PASSWORD, "pass");
ResultActions perform = mvc.perform(builder);
(assertions..)
}
Test was working just fine, until I raised spring-security libs version to 3.2.0.RC1.
Now, I am getting NullPointerException at:
ResultActions perform = mvc.perform(builder);
And the stacktrace is:
java.lang.NullPointerException
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:150)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:137)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:137)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:141)
at com.mycompany.controller.main.LoginControllerTest.test(LoginControllerTest.java:134)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:173)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
I have no idea what to do about it. How to fix that test?
I need this new version of spring-security because it gives support for CSRF attack prevetion.
Greetings,
Peter.
As M. Deinum said, I had to call afterPropertiesSet method on SecurityContextHolderAwareRequestFilter. So the setUp method looks like that:
#Before
public void setUp() throws ServletException {
Mockito.reset(userGroupInfo, licenseManager);
SecurityContextHolderAwareRequestFilter securityContextHolderAwareRequestFilter = new SecurityContextHolderAwareRequestFilter();
securityContextHolderAwareRequestFilter.afterPropertiesSet();
mvc = MockMvcBuilders.standaloneSetup(new LoginController(userGroupInfo, licenseManager, userInfo))
.addFilter(new AnonymousAuthenticationFilter("anonymous"))
.addFilter(securityContextHolderAwareRequestFilter)
.addFilter(new XssValidationFilter()).build();
SecurityContextHolder.getContext().setAuthentication(null);
}
For a REST serives (RESTeasy) I have created JUnit test cases like:
#Test
public void a100_insertAddressTest() throws Exception {
Address addr = new Address(1, "testStreet", "1", (short) 1234,
"testCity");
ClientRequest request = new ClientRequest(BASE_URL + "customerID/{id}",
sslExecutor_schusb);
request.body(MediaType.APPLICATION_XML, addr).pathParameter(
"id", 1);
ClientResponse<String> response = request.post(String.class);
Assert.assertEquals(201, response.getStatus());
response.releaseConnection();
request.clear();
}
If I change the media type of the request body to "application/json", the test case fails with the error:
java.lang.RuntimeException: could not find writer for content-type application/json type: at.fhj.ase.dao.data.Address
at org.jboss.resteasy.client.ClientRequest.writeRequestBody(ClientRequest.java:469)
at org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor.loadHttpMethod(ApacheHttpClient4Executor.java:221)
at org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor.execute(ApacheHttpClient4Executor.java:107)
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:39)
at org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPInterceptor.execute(AcceptEncodingGZIPInterceptor.java:40)
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:45)
at org.jboss.resteasy.client.ClientRequest.execute(ClientRequest.java:443)
at org.jboss.resteasy.client.ClientRequest.httpMethod(ClientRequest.java:674)
at org.jboss.resteasy.client.ClientRequest.post(ClientRequest.java:565)
at org.jboss.resteasy.client.ClientRequest.post(ClientRequest.java:570)
at at.fhj.ase.business.ServiceAddressImplTest.a100_insertAddressTest(ServiceAddressImplTest.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:168)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Hence I created a MessageBodyWriter which works fine if I do a POST request by using the firefox plugin RESTClient:
#Provider
#Produces(MediaType.APPLICATION_JSON)
public class JsonMsbWriter implements MessageBodyWriter<Address> {
#Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
if(type == Address.class){
return true;
}
return false;
}
#Override
public long getSize(Address t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
#Override
public void writeTo(Address t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException,
WebApplicationException {
ObjectMapper m = new ObjectMapper();
m.writeValue(entityStream, t);
}
}
and updated the JUnit test case to:
#Test
public void a100_insertAddressTest() throws Exception {
Address addr = new Address(1, "testStreet", "1", (short) 1234,
"testCity");
ResteasyProviderFactory fact = ResteasyProviderFactory.getInstance();
fact.addMessageBodyWriter(JsonMsbWriter.class);
ClientRequest request = new ClientRequest(BASE_URL + "customerID/{id}",
sslExecutor_schusb);
request.body(MediaType.APPLICATION_JSON, addr).pathParameter("id", 1);
ClientResponse<String> response = request.post(String.class);
Assert.assertEquals(201, response.getStatus());
response.releaseConnection();
request.clear();
}
But now I get the error:
java.lang.VerifyError: (class: org/codehaus/jackson/map/ObjectMapper, method: writeValueAsBytes signature: (Ljava/lang/Object;)[B) Incompatible argument to function
at at.fhj.ase.xmlvalidation.msbreader.JsonMsbWriter.writeTo(JsonMsbWriter.java:46)
at at.fhj.ase.xmlvalidation.msbreader.JsonMsbWriter.writeTo(JsonMsbWriter.java:1)
at org.jboss.resteasy.core.interception.MessageBodyWriterContextImpl.proceed(MessageBodyWriterContextImpl.java:117)
at org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor.write(GZIPEncodingInterceptor.java:100)
at org.jboss.resteasy.core.interception.MessageBodyWriterContextImpl.proceed(MessageBodyWriterContextImpl.java:123)
at org.jboss.resteasy.client.ClientRequest.writeRequestBody(ClientRequest.java:472)
at org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor.loadHttpMethod(ApacheHttpClient4Executor.java:221)
at org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor.execute(ApacheHttpClient4Executor.java:107)
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:39)
at org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPInterceptor.execute(AcceptEncodingGZIPInterceptor.java:40)
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:45)
at org.jboss.resteasy.client.ClientRequest.execute(ClientRequest.java:443)
at org.jboss.resteasy.client.ClientRequest.httpMethod(ClientRequest.java:674)
at org.jboss.resteasy.client.ClientRequest.post(ClientRequest.java:565)
at org.jboss.resteasy.client.ClientRequest.post(ClientRequest.java:570)
at at.fhj.ase.business.ServiceAddressImplTest.a100_insertAddressTest(ServiceAddressImplTest.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:168)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
How can I attach such a writer for json?
And why does it work for content type application/xml out of the
box?
For GET requests and application/json there is the same problem, however with the reader instead of the writer.
Problem solved, unfortunately I haven't included all necessary 3rd party libraries to the projects build path. Finally I added the following jars:
jackson-core-asl-1.6.3.jar
jackson-jaxrs-1.6.3.jar
jackson-mapper-asl-1.6.3.jar
jackson-xc-1.6.3.jar
resteasy-jackson-provider-2.2.1.GA.jar
This example brings the strength of Maven to the front. With Maven there is only one entry necessary to fulfill these dependencies.
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.2.1.GA</version>
</dependency>