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.
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 am getting an exception when I try to run the Spring Web Service JUnit Test Using the Spring WebService ServerSide Integration Test using MockWebServiceClient. When I run the WebService Junit Test, I'm getting an exception:
No endpoint can be found for request [SaajSoapMessagehttp://schemas.xmlsoap.org/soap/envelope/}Envelope]
Spring_WS_ServletConfig
#Configuration
#EnableWs
#EnableTransactionManagement
// #ComponentScan({ "com.springws.endpoint", "com.mybatis.", "com.mapstruct" })
// #ImportResource({ "classpath:/SpringConfig/spring-database-config.xml" })
public class Spring_WS_ServletConfig extends WsConfigurerAdapter {
#Bean("StudentServiceWsdl")
public DefaultWsdl11Definition orders() throws SQLException {
DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
definition.setPortTypeName("StudentService_SpringWS_PortType");
definition.setLocationUri("http://localhost:8080/MvnSpringMcc/StudentService_SpringWS/");
definition.setTargetNamespace("com.springws.student/LearnSpringWs");
definition.setServiceName("SpringWSService");
// definition.setWsdl(new
// ClassPathResource("/wsdl/StudentService.wsdl"));
definition.setSchema(studentsSchema());
return definition;
}
#Bean
public XsdSchema studentsSchema() {
Resource resource = new ClassPathResource("/wsdl/StudentTask.xsd");
return new SimpleXsdSchema(new ClassPathResource("/Schema_Wsdl/StudentTask.xsd"));
}
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
PayloadValidatingInterceptor validator = new PayloadValidatingInterceptor();
validator.setValidateRequest(true);
validator.setValidateResponse(true);
validator.setSchema(new ClassPathResource("/Schema_Wsdl/StudentTask.xsd"));
}
}
TestConfig
#Configuration
#ComponentScan({ "com.springws.test", "com.mybatis.mapper.vo", "com.mybatis.service", "com.mapstruct.mapper",
"com.springws.endpoint", "com.mybatis.mapper" })
//#Import(Spring_WS_ServletConfig.class)
#ImportResource({ "classpath:testResources/spring-ws-test-database-config.xml" })
public class TestConfig {
}
CourseServiceEndPointServerSideIntegrationTest
#EnableTransactionManagement
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { TestConfig.class, Spring_WS_ServletConfig.class })
public class CourseServiceEndPointServerSideIntegrationTest {
#Autowired
ResourceLoader resourceLoader;
#Autowired
private ApplicationContext applicationContext;
private MockWebServiceClient mockClient;
#Before
public void createClient() {
mockClient = MockWebServiceClient.createClient(applicationContext);
}
#Test
public void courseEndpoint() throws Exception {
Resource requestPayLoad = resourceLoader.getResource("classpath:xmlTestFiles/RequestPayLoad.xml");
Resource responsePayLoad = resourceLoader.getResource("classpath:xmlTestFiles/ResponsePayLoad.xml");
mockClient.sendRequest(withPayload(requestPayLoad)).andExpect(payload(responsePayLoad));
}
}
RequestPayLoad.xml File
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:lear="com.springws.student/LearnSpringWs" xmlns:stud="com.springws.student/StudentSchema">
<soapenv:Header />
<soapenv:Body>
<lear:GetCourseRequest>
<lear:Course>
<stud:courseID>100</stud:courseID>
</lear:Course>
</lear:GetCourseRequest>
</soapenv:Body>
</soapenv:Envelope>
Exception
CourseServiceEndpoint(com.springws.endpoint.CourseServiceEndpoint) Time elapsed: 0.219 sec <<< FAILURE!
java.lang.AssertionError: No endpoint can be found for request [SaajSoapMessage {http://schemas.xmlsoap.org/soap/envelope/}Envelope]
at org.springframework.ws.test.support.AssertionErrors.fail(AssertionErrors.java:39)
at org.springframework.ws.test.server.MockWebServiceClient.sendRequest(MockWebServiceClient.java:184)
at com.springws.serverside.test.CourseServiceEndPointServerSideIntegrationTest.courseEndpoint(CourseServiceEndPointServerSideIntegrationTest.java:41)
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:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
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:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
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.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Results :
Failed tests: CourseServiceEndpoint(com.springws.serverside.test.CourseServiceEndPointServerSideIntegrationTest): No endpoint can be found for request [SaajSoapMessage {http://schemas.xmlsoap.org/soap/envelope/}Envelope]
The better way to solve this problem is to change for proper methods in RequestCreators
and ResponseMatchers for SOAP one.
import static org.springframework.ws.test.server.RequestCreators.withSoapEnvelope;
import static org.springframework.ws.test.server.ResponseMatchers.soapEnvelope;
Changes need to be done in our test method.
Before:
mockClient.sendRequest(withPayload(requestPayLoad)).andExpect(payload(responsePayLoad));
After:
mockClient.sendRequest(withSoapEnvelope(requestPayLoad)).andExpect(soapEnvelope(responsePayLoad));
Finally I was able to solve the problem: Just provide the Soap Payload Information in the MockWebServiceClient.sendRequest's withPayload() & andExpect(payload()) methods.
RequestPayLoad.xml
<lear:GetCourseRequest xmlns:lear="com.springws.student/LearnSpringWs"
xmlns:stud="com.springws.student/StudentSchema">
<lear:Course>
<stud:courseID>100</stud:courseID>
</lear:Course>
</lear:GetCourseRequest>
ResponsePayLoad.xml
<ns3:GetCourseResponse xmlns:ns2="com.springws.student/StudentSchema"
xmlns:ns3="com.springws.student/LearnSpringWs">
<ns3:Course>
<ns2:courseID>100</ns2:courseID>
<ns2:courseName>Physics</ns2:courseName>
<ns2:courseCategory>Physics</ns2:courseCategory>
<ns2:credit>3.0</ns2:credit>
</ns3:Course>
</ns3:GetCourseResponse>
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);
}