I'm using Jersey in my REST-application. I need to test it with junit. But I got an com.sun.jersey.api.client.ClientHandlerException. Stacktrace:
SEVERE: The registered message body readers compatible with the MIME media type are:
application/octet-stream ->
com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
com.sun.jersey.core.impl.provider.entity.FileProvider
com.sun.jersey.core.impl.provider.entity.InputStreamProvider
com.sun.jersey.core.impl.provider.entity.DataSourceProvider
com.sun.jersey.core.impl.provider.entity.RenderedImageProvider
*/* ->
com.sun.jersey.core.impl.provider.entity.FormProvider
com.sun.jersey.core.impl.provider.entity.StringProvider
com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
com.sun.jersey.core.impl.provider.entity.FileProvider
com.sun.jersey.core.impl.provider.entity.InputStreamProvider
com.sun.jersey.core.impl.provider.entity.DataSourceProvider
com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General
com.sun.jersey.core.impl.provider.entity.ReaderProvider
com.sun.jersey.core.impl.provider.entity.DocumentProvider
com.sun.jersey.core.impl.provider.entity.SourceProvider$StreamSourceReader
com.sun.jersey.core.impl.provider.entity.SourceProvider$SAXSourceReader
com.sun.jersey.core.impl.provider.entity.SourceProvider$DOMSourceReader
com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General
com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General
com.sun.jersey.core.impl.provider.entity.XMLRootObjectProvider$General
com.sun.jersey.core.impl.provider.entity.EntityHolderReader
com.sun.jersey.api.client.ClientHandlerException: A message body reader for Java class com.example.Student, and Java type class com.example.Student, and MIME media type application/octet-stream was not found
at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:561)
at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:517)
at com.example.servlet.StudentResourceTest.test(StudentResourseTest.java:85)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
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:174)
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 do not know how to fix this bug. I'm looking forward to your help.
My code:
#Path("/student")
#Component
public class StudentResourse {
#Autowired
private StrudentService service;
#Path("/getStudent/{id}")
#GET
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Student getStudent(#PathParam("id") long id) {
return service.get(id);
}
}
This class works fine. When I type in browser: http://127.0.0.1:8080/Application/student/getStudent/100500 it shows me student in xml
My test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:configuration.xml")
#TestExecutionListeners({ DbUnitTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class })
public class StudentResourseTest extends JerseyTest {
#Override
protected AppDescriptor configure() {
return new WebAppDescriptor.Builder("com.example.servlet")
.contextPath("context").build();
}
#Override
protected TestContainerFactory getTestContainerFactory() {
return new HTTPContainerFactory();
}
#Test
#DatabaseSetup("dataset.xml")
public void test() throws UnsupportedEncodingException {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
ClientResponse response = service.path("getStudent").path("100500")
.accept(MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
Student student = (Student) response.getEntity(Student.class);
System.out.println(student);
}
#Override
public URI getBaseURI() {
return UriBuilder.fromUri("http://127.0.0.1:8080/Application/student/")
.build();
}
}
I'm using this dependency:
<dependency>
<groupId>com.sun.jersey.jersey-test-framework</groupId>
<artifactId>jersey-test-framework-http</artifactId>
<version>1.2</version>
</dependency>
Student class marked as #XmlRootElement. Problem is in test class. Any ideas? Thanks for you answers
You're deploying your application to context context-path but then you're assuming (by overriding getBaseURI() method) that the application is deployed on Application context-path. Try to remove the overriding getBaseURI() method and change the test method to following:
#Test
#DatabaseSetup("dataset.xml")
public void test() throws UnsupportedEncodingException {
ClientResponse response = resource()
.path("students").path("getStudent").path("100500")
.accept(MediaType.APPLICATION_XML)
.get(ClientResponse.class);
Student student = (Student) response.getEntity(Student.class);
System.out.println(student);
}
Also check for HTTP response status (should be 200) and response media-type (should be application/xml in this case - if you request application/xml and get application/octet-stream something is clearly wrong).
using below annortation #XmlRootElement
and change library of jersey
AND server log clean after publish the project
Please check A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found
& this link to resolve your issue.I hope it is enough to sort out your problem.
Related
I want to create a Stub for an API and want to verify API call and response returned by the server. for that i have implemented WireMock example :
import org.junit.Rule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class MockTestDemo {
private static final int WIREMOCK_PORT = 8080;
#Rule
public WireMockRule wireMockRule = new WireMockRule(WIREMOCK_PORT);
#Test
public void exampleTest() {
stubFor(get(urlEqualTo("/login")).withHeader("Accept", equalTo("application/json"))
.willReturn(aResponse().withStatus(200).withBody("Login Success")
.withStatusMessage("Everything was just fine!"))
.willReturn(okJson("{ \"message\": \"Hello\" }")));
verify(getRequestedFor(urlPathEqualTo("http://localhost:8080/login"))
.withHeader("Content-Type",equalTo("application/json"))); }
}
But getting below error :
com.github.tomakehurst.wiremock.client.VerificationException: Expected at least one request matching: {
"urlPath" : "localhosturl/login",
"method" : "GET",
"headers" : {
"Content-Type" : {
"equalTo" : "application/json"
}
}
}
Requests received: [ ]
at com.github.tomakehurst.wiremock.client.WireMock.verificationExceptionForNearMisses(WireMock.java:545)
at com.github.tomakehurst.wiremock.client.WireMock.verifyThat(WireMock.java:532)
at com.github.tomakehurst.wiremock.client.WireMock.verifyThat(WireMock.java:511)
at com.github.tomakehurst.wiremock.client.WireMock.verify(WireMock.java:549)
at com.wiremock.test.MockTestDemo.exampleTest(MockTestDemo.java:23)
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: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 com.github.tomakehurst.wiremock.junit.WireMockRule$1.evaluate(WireMockRule.java:73)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
If I comment verify part then test executed successfully also i have verified the same using postman by calling http://localhost:8080/login and it returning response successfully ?
Is any thing I'm missing here ?
In your code you are stubbing out a response and then verifying that a request has been made for that stub. You are not however making a call to the endpoint and so the test is failing.
You need to invoke the endpoint before verifying that it is called.
If you use Apache Commons HttpClient, you could write your test as:
#Test
public void exampleTest() throws Exception {
stubFor(get(urlEqualTo("/login")).withHeader("Accept", equalTo("application/json"))
.willReturn(aResponse().withStatus(200).withBody("Login Success")
.withStatusMessage("Everything was just fine!"))
.willReturn(okJson("{ \"message\": \"Hello\" }")));
String url = "http://localhost:8080/login";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
request.addHeader("Content-Type", "application/json");
request.addHeader("Accept", "application/json");
HttpResponse response = client.execute(request);
verify(getRequestedFor(urlPathEqualTo("/login"))
.withHeader("Content-Type", equalTo("application/json")));
}
Kindly, recommend using a class rule annotation/field (#ClassRule) for JUnit 4 (in those cases, where config could be reused on multiple unit tests).
#Rule could cause unexpected behaviors on async or http requests contexts, when stubs aren't registered yet.
Versions: 2.21.0 -> ... -> 2.31.0.
Note: In my particular case, had multiple tests reusing config and all the requests where executed correctly (debugging & checking mocked responses deserialized onto in-memory DTOs).
Then:
// ... WIREMOCK_PORT
#ClassRule
public static final WireMockClassRule WIRE_MOCK_RULE = new WireMockClassRule(WIREMOCK_PORT); // public
Also, recommend verifying mocked request was made to WireMock registered stubs.
Steps:
Create stub: WIRE_MOCK_RULE.stubFor(get(urlPathMatching(...))) // get, post, ...
Hit mocked endpoint with a Http client
Verify stub was invoked: verify(getRequestedFor(urlPathMatching(...)))
//{get, post, ...}RequestedFor(...) API methods for a particular HTTP request
verify(getRequestedFor(urlPathMatching("a-url-pattern"))); //urlEqualTo, ...
I have rest service(PUT) which I intend to unit test it. I am using RestEasy for the Rest calls.
Here is my Resource :
#Path("/my_person")
public class MyResource {
private MyDAO myDao;
#Inject
public MyResource(MyDao myDao) {
this.myDao = myDao;
}
#PUT
#Timed
#Path("purchase_number/{purchaseNumber}/amount/{amount}/number_of_items")
#Produces(MediaType.APPLICATION_JSON)
public Response getItems(#PathParam("purchaseNumber") String purchaseNumber,
#PathParam("amount") String amount) {
return Response.ok(String.format("{\"items\": %d}", myDao.getItems(purchaseNumber, amount))).build();
}
}
The myDao.getItems returns an integer.
My Test class is as follows :
#RunWith(MockitoJUnitRunner.class)
public class MyResourceTest {
#Mock
private MyDao myDao;
#InjectMock
private MyResource myResource;
private TJWSEmbeddedJaxrsServer server;
private ResteasyClient resteasyClient;
#Before
public void startServer() throws IOException {
resteasyClient = new ResteasyClientBuilder().build();
server = new TJWSEmbeddedJaxrsServer();
server.setPort(PORT);
server.setBindAddress("localhost");
server.getDeployment().getResources().add(myResource);
server.start();
}
#After
public void stopServer() {
if (server != null) {
server.stop();
server = null;
}
}
#Test
public void testWhenValidInputGiven() {
String purchaseNumber = "A57697DF";
String amount = "340";
when(myDao.getItems(purchaseNumber, amount)).thenReturn(10);
Response response = resteasyClient.target("http://localhost:9980/my_person/purchase_number/{purchaseNumber}/amount/{amount}/number_of_items").request().buildPut(Entity.entity("{}", MediaType.APPLICATION_JSON))).invoke();
String text = response.getEntity().toString();
assertEquals(200, resp.getStatus());
assertEquals("{\"items\": 10}", text);
}
}
I get the following error at String text = response.getEntity().toString() since the entity object is null. So does it mean that it didn't create the request at all?
java.lang.NullPointerException
at resources.MyResourceTest.testWhenValidInputGiven(MyResourceTest.java:126)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
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.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
at org.jboss.resteasy.core.SynchronousDispatcher.writeResponse(SynchronousDispatcher.java:427)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:376)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:179)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:220)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
at org.jboss.resteasy.plugins.server.tjws.TJWSServletDispatcher.service(TJWSServletDispatcher.java:40)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at Acme.Serve.Serve$ServeConnection.runServlet(Serve.java:2331)
at Acme.Serve.Serve$ServeConnection.parseRequest(Serve.java:2285)
at Acme.Serve.Serve$ServeConnection.run(Serve.java:2057)
at Acme.Utils$ThreadPool$PooledThread.run(Utils.java:1402)
at java.lang.Thread.run(Thread.java:745)
Have you tried to put / in front of you method path #Path("/purchase_number/{purchaseNumber}/amount/{amount}/number_of_items")
i think the framework misunderstood your path and expect my_personpurchase_number/.
Check your status code on response to see if actually get 200 back or a 404.
The solution to this problem was that I was using
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
instead of
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<version>3.0.10.Final</version>
</dependency>
both had the class javax.ws.rs.core.Response.
Good day. I have a problem with using Arquillian with PowerMock.
I wanna test jax-rs service, but I get two NPEs when test starts.
NullPointerException throws when PowerMockRule field defined.
My test:
#RunWith(Arquillian.class)
#PowerMockIgnore({"javax.management.*", "javax.xml.parsers.*",
"com.sun.org.apache.xerces.internal.jaxp.*", "ch.qos.logback.*", "org.slf4j.*"})
public class ResourceRequestServiceIsAvailableIT {
private static final Logger LOGGER = LoggerFactory
.getLogger(ResourceRequestServiceIsAvailableIT.class);
#Rule
public PowerMockRule rule = new PowerMockRule();
#Deployment(testable = true)
public static Archive<?> createDeployment() {
final WebArchive war = ShrinkWrap
.create(WebArchive.class, "resourceRequestIsAvailableTest.war")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsWebInfResource("wildfly-ds.xml")
.addAsResource("functionalId.properties")
.addAsResource("logback-test.xml", "logback.xml")
.addAsResource("xml/organizationalUnit.xml")
.addAsResource("xsd/organizationalUnit.xsd")
.addAsResource("xml/resourceRequest.xml")
.addAsResource("xsd/resourceRequest.xsd")
.addClass(ResourceRequestRestService.class)
.addPackages(true, "by.iba.gomel.domain")
.addPackage("by.iba.gomel.restws.logging")
.addPackages(true, "org.apache.commons.io")
.addAsLibraries(
Maven.resolver().resolve("org.kie.remote:kie-remote-client:6.2.0.Final")
.withTransitivity().asFile())
.addAsLibraries(
Maven.resolver().resolve("org.aspectj:aspectjrt:1.8.5").withTransitivity()
.asFile());
ResourceRequestServiceIsAvailableIT.LOGGER.info("generated .war file - "
+ war.toString(true) + "\n");
return war;
}
#Test
public void testStartResourceRequest() {
final ResteasyClient client = new ResteasyClientBuilder().build();
final ResteasyWebTarget target = client.target("http" + "://" + "localhost" + ":" + "8080"
+ "/resourceRequestIsAvailableTest" + "/rest/resourcerequest/startResourceRequest");
final Form form = new Form();
try {
form.param("rr", IOUtils.toString(ResourceRequestServiceIsAvailableIT.class
.getResourceAsStream("/xml/resourceRequest.xml")));
} catch (final IOException e) {
ResourceRequestServiceIsAvailableIT.LOGGER.error(
MarkerFactory.getMarker(LoggerConstants.EXCEPTION_LOG_MARKER.getString()),
"Problem reading ResourceRequest XML", e);
}
try {
form.param("ou", IOUtils.toString(ResourceRequestServiceIsAvailableIT.class
.getResourceAsStream("/xml/organizationalUnit.xml")));
} catch (final IOException e) {
ResourceRequestServiceIsAvailableIT.LOGGER.error(
MarkerFactory.getMarker(LoggerConstants.EXCEPTION_LOG_MARKER.getString()),
"Problem reading OrganizationalUnit XML", e);
}
final Response response = target.request().post(Entity.form(form));
ResourceRequestServiceIsAvailableIT.LOGGER.info(
"Request successfully sent, response is '{}'", response.getStatusInfo());
response.close();
}
}
My service method:
#POST
#Path("/startResourceRequest")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response postAll(final MultivaluedMap<String, String> form) {
final URL baseUrl;
ResourceRequest resourceRequest = null;
try {
final JAXBContext jaxbContext = JAXBContext.newInstance(ResourceRequest.class,
OrganizationalUnit.class);
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
resourceRequest = (ResourceRequest) unmarshaller.unmarshal(new StringReader(form
.getFirst("rr")));
baseUrl = new URL("http://localhost:8084/kie-wb");
} catch (final JAXBException | MalformedURLException e) {
ResourceRequestRestService.LOGGER.error(
MarkerFactory.getMarker(LoggerConstants.EXCEPTION_LOG_MARKER.getString()),
"System problem, check the log", e);
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity("System problem, check the log").build();
}
if (form.containsKey("userId")) {
this.user = form.getFirst("userId");
this.password = form.getFirst("password");
}
if ((this.user == null) || this.user.isEmpty()) {
ResourceRequestRestService.LOGGER.error(
MarkerFactory.getMarker(LoggerConstants.EXCEPTION_LOG_MARKER.getString()),
"Failed to provide authentication data");
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity("Failed to provide authentication data").build();
}
final RuntimeEngine engine = RemoteRuntimeEngineFactory.newRestBuilder()
.addDeploymentId(ResourceRequestRestService.DEPLOYMENT_ID).addUrl(baseUrl)
.addUserName(this.user).addPassword(this.password)
.addExtraJaxbClasses(ResourceRequest.class).build();
final KieSession ksession = engine.getKieSession();
final Map<String, Object> processParams = new HashMap<>();
processParams.put("resourceRequest", resourceRequest);
ksession.startProcess("Interview.ResourceRequest", processParams);
return Response.status(Status.OK).entity("Business process 'Resource Request' started")
.build();
}
Stacktrace:
java.lang.NullPointerException: null
at org.jboss.arquillian.junit.Arquillian$4.evaluate(Arquillian.java:222)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:314)
at org.jboss.arquillian.junit.Arquillian.access$100(Arquillian.java:46)
at org.jboss.arquillian.junit.Arquillian$5.evaluate(Arquillian.java:240)
at org.powermock.modules.junit4.rule.PowerMockStatement$1.run(PowerMockRule.java:52)
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.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:2014)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:885)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:713)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
at org.powermock.classloading.ClassloaderExecutor.execute(ClassloaderExecutor.java:98)
at org.powermock.classloading.ClassloaderExecutor.execute(ClassloaderExecutor.java:78)
at org.powermock.modules.junit4.rule.PowerMockStatement.evaluate(PowerMockRule.java:49)
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.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:185)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:314)
at org.jboss.arquillian.junit.Arquillian.access$100(Arquillian.java:46)
at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:199)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:147)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
java.lang.NullPointerException: null
at org.jboss.arquillian.junit.Arquillian$5$1.evaluate(Arquillian.java:245)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:314)
at org.jboss.arquillian.junit.Arquillian.access$100(Arquillian.java:46)
at org.jboss.arquillian.junit.Arquillian$5.evaluate(Arquillian.java:240)
at org.powermock.modules.junit4.rule.PowerMockStatement$1.run(PowerMockRule.java:52)
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.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:2014)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:885)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:713)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
at org.powermock.classloading.ClassloaderExecutor.execute(ClassloaderExecutor.java:98)
at org.powermock.classloading.ClassloaderExecutor.execute(ClassloaderExecutor.java:78)
at org.powermock.modules.junit4.rule.PowerMockStatement.evaluate(PowerMockRule.java:49)
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.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:185)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:314)
at org.jboss.arquillian.junit.Arquillian.access$100(Arquillian.java:46)
at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:199)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:147)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Please, help to find solution. May be some body knows what's wrong.
Your problems seems very similar to a post in Jboss forums here.
Please checkit out. May be that helps.
Regards
Himanshu
I'm calling a REST service using this test code:
public class TestRESTServices {
private static final String BASE_URL = "http://localhost/ma.ge.persistence-1.0/rest/reference";
private static URI uri = UriBuilder.fromUri(BASE_URL).port(8080).build();
private static Client client = ClientBuilder.newClient();
#Test
public void createAndDeleteAReference() {
Reference r = ReferenceFactory.createReference("Maz",
"dummy", 1.7);
Response response = client.target(uri).request().post(Entity.entity(r, MediaType.APPLICATION_JSON));
assertEquals(Response.Status.CREATED, response.getStatusInfo());
URI referenceURI = response.getLocation();
// Get the posted reference
response = client.target(referenceURI).request().get();
Reference retreivedRef = response.readEntity(Reference.class);
assertEquals(Response.Status.OK, response.getStatusInfo());
assertEquals(retreivedRef.getName(), r.getName());
}
But I get the following error:
javax.ws.rs.ProcessingException: Unable to invoke request
at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:287)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:407)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilder.get(ClientInvocationBuilder.java:159)
at ma.gesto.persistence.TestRESTServices.createAndDeleteAReference(TestRESTServices.java:34)
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.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)
Caused by: java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
at org.apache.http.impl.conn.BasicClientConnectionManager.getConnection(BasicClientConnectionManager.java:162)
at org.apache.http.impl.conn.BasicClientConnectionManager$1.getConnection(BasicClientConnectionManager.java:139)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:456)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:283)
... 26 more
The Client interface represents external resources. As such, it is a critical mistake to create and store one in a static variable. This is wrong:
private static Client client = ClientBuilder.newClient();
This is ok for unit testing:
private Client client;
#Before
public void setUp() {
this.client = ClientBuilder.newClient();
}
#After
public void tearDown() {
this.client.close();
}
In normal code you would want to wrap Client usage in a try-with-resources or try..finally:
Client client = ClientBuilder.newClient();
try {
// use the client to make requests
} finally {
client.close();
}
Ideally there would be a way to manage a pool of Client instances for reuse.
You also need to close your Response to free up the connection.
See explanations here:
Resteasy Client keeping connection allocated after a method throws an Exception
I'm testing an api endpoint which works from a http poster (namely PAW) but I cant get a test in the code to pass.
I'm new to both Mockito and MockMVC so any help would be appreciated.
Test below:
#Test
public void createPaymentTest() throws Exception {
User user = new User("ben", "password", "a#a.com");
SuccessResponseDTO successDTO = new SuccessResponseDTO();
successDTO.setSuccess(true);
when(userService.getLoggedInUser()).thenReturn(user);
when(paymentService.makePayment(Mockito.any(PaymentRequestDTO.class), Mockito.any(User.class))).thenReturn(successDTO.getSuccess());
this.mockMvc.perform(post("/payment")).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultHandlers.print())
.andExpect(jsonPath("$.success").value(successDTO.getSuccess()));
}
SuccessResponseDTO just contains one attribute, a boolean 'success'.
The method it's testing is below:
#RequestMapping(value = "/payment", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public SuccessResponseDTO createPayment(#RequestBody PaymentRequestDTO payment) {
User loggedInUser = userService.getLoggedInUser();
LOGGER.info("Logged in user found...creating payment...");
Assert.notNull(payment.getAccountId(), "Missing user account id");
Assert.notNull(payment.getPayeeAccountNumber(), "Missing payee acount number");
Assert.notNull(payment.getPayeeName(), "Missing payee name");
Assert.notNull(payment.getPayeeSortCode(), "Missing payee sort code");
Assert.notNull(payment.getPaymentAmount(), "Missing payee amount");
Assert.notNull(payment.getPaymentDescription(), "Missing payment description");
Boolean paymentResult = paymentService.makePayment(payment, loggedInUser);
SuccessResponseDTO successResponse = new SuccessResponseDTO();
successResponse.setSuccess(paymentResult);
return successResponse;
}
Can anyone shed light on the stack trace:
java.lang.AssertionError: Status expected:<200> but was:<415>
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$5.match(StatusResultMatchers.java:546)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)
at com.capco.living.controller.PaymentControllerTest.createPaymentTest(PaymentControllerTest.java:69)
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: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)
HTTP Error 415 Unsupported media type - means that you send the data which is not supported by the service. In this case it means that you don't set the Content-Type header and actual content in the request. I suppose the JSON is expected content, so your call should look like this:
this.mockMvc.perform(post("/payment").contentType(MediaType.APPLICATION_JSON)
.content("{\"json\":\"request to be send\"}"))
.andExpect(status().isOk())
.and_the_rest_of_validation_part
You might also be missing some annotations on your controller class. Make sure you use #EnableWebMvc and #Controller
Check out this answer for details
Also you might add accept
mockMvc.perform(post("/api/sender/sms/")
.accept(MediaType.APPLICATION_JSON_UTF8)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content("{ \"serviceName\":\"serviceName\", \"apiId\":\"apiId\", \"to\":\"to\", \"msg\":\"msg\" }")
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();