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
Related
This is my test method:
#RunWith(Parameterized.class)
#PrepareForTest(FilenameUtils.class)
public class Test {
//code
private final String datum;
private final String expectedResult;
public Test(String datum, String expectedResult){
this.datum = datum;
this.expectedResult = expectedResult;
}
#Parameters
public static Collection<Object[]> generateData(){
return Arrays.asList(new Object[][] {
{ ".jpg", "productimage..jpg" },
{ "jpg", "jpg.jpeg" },
{ "thequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydog.jpeg", "thequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjump.jpeg" }
});
}
#Before
public void setUp() {
}
#After
public void tearDown() {
}
#Test
public void testSanitizeFilename(){
PowerMock.mockStaticPartial(FilenameUtils.class, "getExtension" , "getBaseName");
expect(FilenameUtils.getExtension(datum)).andReturn("jpeg").anyTimes();
expect(FilenameUtils.getBaseName(datum)).andReturn("productimage").anyTimes();
PowerMock.replay(FilenameUtils.class);
String result = FileUtil.sanitizeFilename(datum, defaultName, contentType);
PowerMock.verify(FilenameUtils.class);
assertEquals(result, expectedResult);
}
}
And this is the method to be tested:
public class FileUtil {
//code
public static String sanitizeFilename(String filename, ............) {
//code here
if (filename.length() > 100) {
FilenameUtils.getExtension(fileName);
FilenameUtils.getBaseName(fileName);
}
return fileName;
}
}
The code works only for the cases that the condition in FileUtil.sanitizeFilename is not true. If it is true (by passing a filename > 100 characters), then the following error occurs:
Unexpected method call FilenameUtils.getExtension("thequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydog.jpeg"):
java.lang.AssertionError
Unexpected method call FilenameUtils.getExtension("thequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydogthequickbrownfoxjumpsoverthelazydog.jpeg"):
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl.invoke(EasyMockMethodInvocationControl.java:91)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:105)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:60)
at org.apache.commons.io.FilenameUtils.getExtension(FilenameUtils.java)
at com.eurodyn.ecatalogue.util.FileUtil.sanitizeFilename(FileUtil.java:235)
at com.eurodyn.ecatalogue.ejb.session.others.AsyncFileDownloadManagerBeanTest.testSanitizeFilename(AsyncFileDownloadManagerBeanTest.java:130)
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.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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.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.runners.ParentRunner.run(ParentRunner.java:309)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
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:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
What is incorrect in my code?
EDIT:
I used Parameterized class in order to avoid the for loop.
I used PowerMock.mockStaticPartial for the static methods getBaseName and getExtension.
How it worked for me
#Test
public void testSanitizeFilename() {
PowerMock.mockStatic(FilenameUtils.class);
EasyMock.expect(FilenameUtils.getExtension(anyString())).andReturn("jpeg").anyTimes();
EasyMock.expect(FilenameUtils.getBaseName(anyString())).andReturn("jpeg").anyTimes();
PowerMock.replayAll();
for (Map.Entry<String, String> entry : fileUrls.entrySet()) {
System.out.println("KEY: " + entry.getKey());
String result = FileUtil.sanitizeFilename(entry.getKey(), entry.getValue());
assertEquals(result, entry.getValue());
PowerMock.verifyAll();
}
}
Note that I modified sanitizeFilename some to get working code for me. And I used
#Rule
public PowerMockRule rule = new PowerMockRule();
instead of RunWith - but as I had all your errors before this might fix your stuff as well.
Seems like mocking inside the loop was no good idea to begin with - once I moved the mocks out of the loop it got me somewhere.
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.
http://localhost:8080/solr works well in my browser and there is no error in the console of tomcat when I start it.
my code is:
public static void index() throws SolrServerException, IOException {
String url = "http://localhost:8080/solr";
HttpSolrServer server = new HttpSolrServer(url);
SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", "1");
doc.addField("name", "name");
doc.addField("content", "cold today");
server.add(doc);
server.commit();
}
when I run the code,there is nothing printed in the console of tomcat and I get
Caused by: org.apache.http.NoHttpResponseException: The target server failed to respond instead.
the full failure trace is:
org.apache.solr.client.solrj.SolrServerException: IOException occured when talking to server at: http://localhost:8080/solr
at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:507)
at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:199)
at org.apache.solr.client.solrj.request.AbstractUpdateRequest.process(AbstractUpdateRequest.java:118)
at org.apache.solr.client.solrj.SolrServer.add(SolrServer.java:116)
at org.apache.solr.client.solrj.SolrServer.add(SolrServer.java:102)
at com.cc.solr.SolrDemo.index(SolrDemo.java:21)
at com.cc.solr.TestSolrDemo.testIndex(TestSolrDemo.java:16)
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:483)
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)
Caused by: org.apache.http.NoHttpResponseException: The target server failed to respond
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:143)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:57)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:260)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:283)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:251)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:197)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:271)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:123)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:682)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:486)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:395)
... 29 more
I think here is something wrong in my computer but I can not figure out.
I have tried solr 4.6.0 and solr 4.7.2,both of them failed.
It fails when running this code:
final HttpResponse response = httpClient.execute(method);
in HttpSolrServer.java(line number 395 in 4.7.2)
But when I copied the project to my roommate's computer ,it worked fine.
It's very wierd.It seems that the request is successfully accepted by server and if I change my code like:
public static void index() throws SolrServerException, IOException {
String url = "http://localhost:8080/solr";
HttpSolrServer server = new HttpSolrServer(url);
server.setSoTimeout(10000);
SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", "3");
doc.addField("name", "name3");
doc.addField("content", "cold today3");
try{
server.add(doc);
}catch(Exception e){
e.printStackTrace(); //time out
}
server.commit();
}
It still prints exception message but it works...
I am running a simple JUnit test. The test is:
private HangmanModel model;
private WordsToGuess word;
public void setUp()
{
model = new HangmanModel();
word = new WordsToGuess();
}
#Test
public void addWordAndChoose()
{
WordsToGuess testWord = new WordsToGuess("ahoy");
model.addWord(testWord); <---- NullPointerException
String foundWord = model.randomWord();
assertEquals("Not found the word", testWord, foundWord);
}
In WordsToGuess, the constructor is:
public WordsToGuess(String w)
{
word = w;
}
In HangmanModel, the addWord method is:
private ArrayList<WordsToGuess> words;
words = new ArrayList<WordsToGuess>();
public void addWord(WordsToGuess w)
{
words.add(w);
}
This is a REALLY weird NullPointerException since everything should run perfectly fine. It is copied almost word for word from a similar project. Here is the Stack trace:
java.lang.NullPointerException
at testing.HangmanModelTest.addWordAndChoose(HangmanModelTest.java:22)
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: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)
The #Before annotation is required before the setup method for JUnit 4
#Before
public void setUp() {
...
}
I have been trying to setup my test framework for Spring data neo4j (version 3.0.1.RELEASE) application. I am using pure java config to setup my test cases.
This is my TestConfig class
#Configuration
#EnableTransactionManagement
#EnableNeo4jRepositories(basePackages = {"com.sitename.data.repository"})
#ComponentScan(basePackages = "com.sitename.data")
public class TestDataConfig extends Neo4jConfiguration {
#Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
return new TestGraphDatabaseFactory().newImpermanentDatabase();
}
#Bean
public Neo4jTemplate neo4jTemplate() {
return new Neo4jTemplate(graphDatabaseService());
}
}
And this is my test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class TestClass {
private UserService userService = UserService.getInstance();
#BeforeClass
public static void setup() {
BaseService.configure(TestDataConfig.class);
}
#Before
public void addData() {
saveOneUser("test#email.com");
}
#Test
public void testMe() {
Assert.assertEquals(0, userService.findAll().size());
}
private User saveOneUser(String email) {
try {
User user = new User();
user.setEmail(email);
user.setFirstName( new Integer(new Random(new Date().getTime()).nextInt(17) + 1).toString() );
return userService.save( user );
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
return null;
}
}
Every time i run the test i am getting the Failed to mark transaction as rollback only error.
Full stacktrace
-------------------------------------------------------------------------------
Test set: com.sitename.TestClass
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 6.416 sec <<< FAILURE!
testMe(com.sitename.TestClass) Time elapsed: 0.406 sec <<< ERROR!
org.neo4j.graphdb.TransactionFailureException: Failed to mark transaction as rollback only.
at org.neo4j.kernel.TopLevelTransaction.markAsRollbackOnly(TopLevelTransaction.java:97)
at org.neo4j.kernel.TopLevelTransaction.failure(TopLevelTransaction.java:86)
at org.neo4j.cypher.internal.spi.v2_0.TransactionBoundExecutionContext.close(TransactionBoundExecutionContext.scala:58)
at org.neo4j.cypher.internal.compiler.v2_0.spi.DelegatingQueryContext.close(DelegatingQueryContext.scala:32)
at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext.org$neo4j$cypher$internal$compiler$v2_0$spi$ExceptionTranslatingQueryContext$$super$close(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext$$anonfun$close$1.apply$mcV$sp(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext$$anonfun$close$1.apply(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext$$anonfun$close$1.apply(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext.org$neo4j$cypher$internal$compiler$v2_0$spi$ExceptionTranslatingQueryContext$$translateException(ExceptionTranslatingQueryContext.scala:149)
at org.neo4j.cypher.internal.compiler.v2_0.spi.ExceptionTranslatingQueryContext.close(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_0.ClosingIterator.failIfThrows(ClosingIterator.scala:94)
at org.neo4j.cypher.internal.compiler.v2_0.ClosingIterator.next(ClosingIterator.scala:45)
at org.neo4j.cypher.internal.compiler.v2_0.PipeExecutionResult.next(PipeExecutionResult.scala:168)
at org.neo4j.cypher.internal.compiler.v2_0.PipeExecutionResult.next(PipeExecutionResult.scala:34)
at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
at scala.collection.convert.Wrappers$IteratorWrapper.next(Wrappers.scala:30)
at org.neo4j.cypher.internal.compiler.v2_0.PipeExecutionResult$$anon$1.next(PipeExecutionResult.scala:76)
at org.neo4j.helpers.collection.IteratorWrapper.next(IteratorWrapper.java:47)
at org.neo4j.helpers.collection.IteratorWrapper.next(IteratorWrapper.java:47)
at org.neo4j.helpers.collection.IteratorUtil.addToCollection(IteratorUtil.java:478)
at org.neo4j.helpers.collection.IteratorUtil.addToCollection(IteratorUtil.java:557)
at org.springframework.data.neo4j.conversion.ContainerConverter.toContainer(ContainerConverter.java:34)
at org.springframework.data.neo4j.conversion.QueryResultBuilder$1.as(QueryResultBuilder.java:128)
at com.sitename.data.service.UserService.findAll(UserService.java:20)
at com.sitename.TestClass.testMe(TestClass.java:40)
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.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: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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
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:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: java.lang.NullPointerException
at org.neo4j.kernel.TopLevelTransaction.markAsRollbackOnly(TopLevelTransaction.java:93)
... 60 more
Help is appreciated. TIA !
Try and add
#Transactional
on top of your test class to run your tests within a transaction.