NullPointerExecption failure when creating unit test for java spring controller - java

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
}

Related

HTTP 500 Request Failed jerseytest

I just want to test my web services, I'm in Java 1.6 and I use jerseyTest 2.6 for that but I keep getting the error 500 and I don't know why. My test class extends JerseyTest and I have a configure fonction which look like that:
#Override
protected Application configure() {
enable(TestProperties.LOG_TRAFFIC);
enable(TestProperties.DUMP_ENTITY);
ResourceConfig config = new ResourceConfig();
config.register(OrderService.class);
return config;
}
And a simple java class to call the web services :
#XmlRootElement
#Path("/orders")
public class OrderService {
public OrderService() {
}
#GET
public String test() {
return "test";
}
#POST
#Produces({ MediaType.APPLICATION_JSON })
public String echo() {
System.out.println("je suis dans le post");
return "je suis post";
}
#GET
#Produces({ MediaType.TEXT_PLAIN })
#Path("/{orderId}")
public String getOrders(#PathParam("orderId") String orderId) {
System.out.println("je suis passé");
return "orderId: " + orderId;
}
#GET
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
#Path("/summary")
public Response getOrdersSummary() {
return Response.status(Status.OK).entity("orders summary").build();
}
But when I execute the JUnit test I always get
"javax.ws.rs.InternalServerErrorException: HTTP 500 Request Failed"
Can you help me because I'm kinda lost now.
EDIT 1 : The exact trace of the error is :
java.lang.Error: HTTP 500 Request failed.
at com.ideosante.rh.rest.v10.implementation.RessourceSituationFamilialeTest.hello(RessourceSituationFamilialeTest.java:76)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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)
So I don't get what is the problem precisely.

NullPointerException while running JUnit

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 {

java.lang.AssertionError: expected:<200> but was:<404> in jersey restful services unit 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.

Mockito cast ActionForm to Class

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);

Spring mocked junit tests throw NullPointerException with spring-security 3.2.0.RC1 version

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);
}

Categories