I'm trying to mock the java.lang.reflect.Method, here my code:
#RunWith(PowerMockRunner.class)
#PrepareForTest(Method.class)
public class AuditDataTest {
#Test
public void testStartAudit() {
Object[] args = new Object[1];
args[0] = "bla";
Method method = PowerMockito.mock(Method.class);
when(method.getAnnotation(Audit.class).value()).thenReturn("audit");
auditData.startAudit(method, args);
}
}
When i run the test, i get following error message:
java.lang.IllegalAccessError: java.lang.Class
at sun.reflect.GeneratedSerializationConstructorAccessor10.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:40)
at org.powermock.reflect.internal.WhiteboxImpl.newInstance(WhiteboxImpl.java:257)
at org.powermock.reflect.Whitebox.newInstance(Whitebox.java:139)
at org.powermock.core.DefaultFieldValueGenerator.instantiateFieldType(DefaultFieldValueGenerator.java:74)
at org.powermock.core.DefaultFieldValueGenerator.fillWithDefaultValues(DefaultFieldValueGenerator.java:51)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:60)
at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138)
at my.package.audit.AuditDataTest.testStartAudit(AuditDataTest.java:52)
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.internal.runners.TestMethod.invoke(TestMethod.java:59)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:322)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:309)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:297)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:222)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:161)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:135)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:133)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:112)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
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)
Can someone explain me, what i'm doing wrong?
From the Powermock FAQ:
I cannot mock classes in from java.lang, java.net, java.io or other
system classes, why?
This is because they're loaded by Java's bootstrap classloader and cannot be
byte-code manipulated by PowerMock's classloader. Since
PowerMock 1.2.5 there's a work-around, please have a look at this
simple example to see how it's done.
Related
I am currently writing a unit test. but mockito crashes when I tried to mock a DAO interface.
Below is the test code. It basically just trying to mock an interface.
class RepoTest {
#Test
fun testDelete() {
val dao = Mockito.mock(ExchangeRateItemMainPageDAO::class.java)
}
}
And the DAO interface code is as below:
#Dao
interface ExchangeRateItemMainPageDAO {
#Insert
fun insertExchangeRateItem(item: ExchangeRateItemMainPage)
#Delete
fun deleteExchangeRateItem(item:ExchangeRateItemMainPage)
}
Where as the message given when the test failed is below:
java.lang.ExceptionInInitializerError
at org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter.<init>(ConditionalStackTraceFilter.java:17)
at org.mockito.exceptions.base.MockitoException.filterStackTrace(MockitoException.java:41)
at org.mockito.exceptions.base.MockitoException.<init>(MockitoException.java:30)
at org.mockito.exceptions.misusing.MockitoConfigurationException.<init>(MockitoConfigurationException.java:18)
at org.mockito.internal.configuration.plugins.PluginLoader.loadImpl(PluginLoader.java:66)
at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:24)
at org.mockito.internal.configuration.plugins.PluginRegistry.<init>(PluginRegistry.java:12)
at org.mockito.internal.configuration.plugins.Plugins.<clinit>(Plugins.java:11)
at org.mockito.internal.util.MockUtil.<clinit>(MockUtil.java:24)
at org.mockito.internal.MockitoCore.<init>(MockitoCore.java:44)
at org.mockito.Mockito.<clinit>(Mockito.java:975)
at com.lazyfire.curencyexchg.currencypawn.viewModel.RepoTest.testDelete(MainActivityViewModelTest.kt:28)
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: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.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
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.junit.runner.JUnitCore.run(JUnitCore.java:137)
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)
Caused by: java.lang.NullPointerException
at org.mockito.internal.configuration.plugins.Plugins.getStackTraceCleanerProvider(Plugins.java:17)
at org.mockito.internal.exceptions.stacktrace.StackTraceFilter.<clinit>(StackTraceFilter.java:21)
... 36 more
Sorry, just something went wrong in cache. Just invalidate cache and restart and it works fine then.
I know there are lots of question about that, but the problem is that, I searched and googled everything around it, but nothing found that could help me.
I try to implement SOAP based web service client using Apache CXF/Wildfly 8x/Java 1.7/Maven 3+/Eclipse.
I generate proxy classes successfully, implemented ws-security options, add keystore and trustore, but found a very strange problem.
[io.undertow.request] (default task-18) UT005023: Exception handling request to /service/DummyServiceCaller: java.lang.NoClassDefFoundError: org/apache/cxf/frontend/ClientProxy
at com.ddrc.service.Service.core.config.ServiceManager.beforeExecute(ServiceManager.java:17) [:]
at com.ddrc.service.service.core.ServiceManager.executeService(ServiceServiceManager.java:36) [:]
at com.ddrc.service.DummyServiceCaller.doGet(DummyServiceCaller.java:37) [:]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar:1.0.0.Final]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar:1.0.0.Final]
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:63) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.jrHandle(ServletInitialHandler.java) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at org.zeroturnaround.javarebel.integration.servlet.undertow.cbp.ServletInitialHandlerCBP.handleRequest(ServletInitialHandlerCBP.java:100) [undertow-servlet-jr-plugin-6.2.7.jar:]
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:261) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:247) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:76) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:166) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:197) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:759) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [jrebel-bootstrap-39173be574c0f43be80eb922241c6711.jar:1.7.0_75]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [jrebel-bootstrap-39173be574c0f43be80eb922241c6711.jar:1.7.0_75]
at java.lang.Thread.run(Thread.java:745) [jrebel-bootstrap-39173be574c0f43be80eb922241c6711.jar:1.7.0_75]
As i read about that exception, it means that,
This is caused when there is a class file that your code depends on
and it is present at compile time but not found at runtime. Look for
differences in your build time and runtime classpaths.
Source stackoverflow explanation
Of course, I cleaned and rebuild project, restart eclipse but no reaction.
Then I made a simple small project and copied the code there, still same problem.
Then I searched the class in maven repos, found it, opened jar and found the class too.
Then I created runnable jar and copied in my mates PC, checked there and same problem.
Searched a lot but nothing special found.
The only interesting article I found was here CXF but could not understand.
ClientProxy.getClient(proxy) is no longer needed for most use cases.
The client proxy instances now implement the Client API directly. A
direct cast to Client should work.
I do not even know how to start fixing this, how to debug this. Here is the code I wrote.
private void adjustServiceConfiguration(Object port, String address) throws IOException {
org.apache.cxf.endpoint.Client client = ClientProxy.getClient(port);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(/* uccConnectionTimeout.value() */6 * 1000);
httpClientPolicy.setReceiveTimeout(/* uccTimeout.value() */7 * 1000);
http.setClient(httpClientPolicy);
((BindingProvider) port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, address);
((BindingProvider) port).getRequestContext().put("set-jaxb-validation-event-handler", "false");
Map<String, Object> outProps = new HashMap<>();
outProps.put(WSHandlerConstants.ACTION, "Timestamp Signature Encrypt");//
outProps.put(WSHandlerConstants.PASSWORD_TYPE, "PasswordDigest");
outProps.put(WSHandlerConstants.USER, "ucc-agent");
outProps.put(WSHandlerConstants.SIGNATURE_USER, "ucc-agent");
outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, "com.ddrc.service.service.ws.KeyStorePasswordsCallback");
outProps.put(WSHandlerConstants.ENCRYPTION_USER, "ucc");
if (encryptionProps == null || signProps == null) {
try {
encryptionProps = new Properties();
signProps = new Properties();
try (FileInputStream fis1 = new FileInputStream(
uccEncryptionPropFile);
FileInputStream fis2 = new FileInputStream(
uccSignaturePropFile);) {
encryptionProps.load(fis1);
signProps.load(fis2);
}
} catch (IOException ex) {
throw ex;
// log.error("Error occurred during UCC WS-Security configuration file lookup",
// ex);
}
}
outProps.put("encryptionProps", encryptionProps);
outProps.put("signProps", signProps);
outProps.put(WSHandlerConstants.ENC_PROP_REF_ID, "encryptionProps");
outProps.put(WSHandlerConstants.SIG_PROP_REF_ID, "signProps");
Map<String, Object> inProps = new HashMap<>();
inProps.put(WSHandlerConstants.ACTION, "Timestamp Signature Encrypt");
inProps.put(WSHandlerConstants.PASSWORD_TYPE, "PasswordText");
inProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, "com.ddrc.service.service.ws.KeyStorePasswordsCallback");
inProps.put(WSHandlerConstants.ALLOW_RSA15_KEY_TRANSPORT_ALGORITHM, "true");
inProps.put("signProps", signProps);
inProps.put("encryptionProps", encryptionProps);
inProps.put(WSHandlerConstants.DEC_PROP_REF_ID, "signProps");
inProps.put(WSHandlerConstants.SIG_PROP_REF_ID, "encryptionProps");
client.getInInterceptors().add(new WSS4JInInterceptor(inProps));
client.getOutInterceptors().add(new WSS4JOutInterceptor(outProps));
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
}
The problem is in ClientProxy class
Here is an error from small project.
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/cxf/common/i18n/UncheckedException
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at ge.test.Run.main(Run.java:16)
Caused by: java.lang.ClassNotFoundException: org.apache.cxf.common.i18n.UncheckedException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 13 more
and the whole class :)
package ge.test;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
public class Run {
public static void main(String[] args) {
Client c = ClientProxy.getClient(null);
}
}
I don't know why I have that error with mockito
java.lang.NoClassDefFoundError: org/objenesis/ObjenesisStd
at org.mockito.internal.creation.jmock.ClassImposterizer.<init>(ClassImposterizer.java:36)
at org.mockito.internal.creation.jmock.ClassImposterizer.<clinit>(ClassImposterizer.java:29)
at org.mockito.internal.util.MockCreationValidator.isTypeMockable(MockCreationValidator.java:17)
at org.mockito.internal.util.MockCreationValidator.validateType(MockCreationValidator.java:21)
at org.mockito.internal.creation.MockSettingsImpl.validatedSettings(MockSettingsImpl.java:133)
at org.mockito.internal.creation.MockSettingsImpl.confirm(MockSettingsImpl.java:127)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:50)
at org.mockito.Mockito.mock(Mockito.java:1243)
at org.mockito.Mockito.mock(Mockito.java:1120)
at fr.oap.SubscriptionTest.testGetSubscriptionById(SubscriptionFactoryTest.java:24)
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 junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
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: java.lang.ClassNotFoundException: org.objenesis.ObjenesisStd
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 29 more
About my class of Test is like this :
import junit.framework.TestCase;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import fr.aop.subscription.AbstractSubscription;
public class SubscriptionTest extends TestCase {
#Test
public void testGetSubscriptionById() {
ArgumentCaptor<AbstractSubscription>
arg=ArgumentCaptor.forClass(AbstractSubscription.class);
Subscription objMock=Mockito.mock(Subscription.class);
Mockito.when(objMock.getSubscribById(1)).thenReturn(arg.getValue());
}
}
And about the method getSubscribById whitch is in the class Subscription:
#Override
public AbstractSubscription getSubscriptionById(final Integer id) {
this.log.debug("BEGIN: getSubscriptionById id = " + id);
AbstractSubscription obj = null;
if (id != null) {
final StringBuilder queryString = new StringBuilder("select c from AbstractSubscription c ");
try {
queryString.append("where c.id = :id");
Query query = this.getEntityManager().createQuery(queryString.toString());
query = query.setParameter("id", id);
obj = (AbstractSubscription) query.getSingleResult();
} catch (final Exception exc) {
}
}
return obj;
}
when I instanciate the Subcription class it demand me the connection to the database, that's why I want to escape this and looking for a solution like mockito
ClassNotFoundException is result of a class loader that is not able to load a particular class.
In your case Mockito has a transitive dependency to Objenesis (it needs Objenesis for correct behavior). You are most likely trying to execute your test with Mockito on test class path, but without Objenesis.
You need to add Objenesis to your test class path.
For maven projects, be sure that:
you have declared Mockito as test dependency
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
to run a particular test from the command line execute
mvn test -Dtest=fullyQualifedNameToYourTestClass
You can try adding the mockito-all artifact instead of mockito-core, it works since version 1.9.5
I had a similar problem in an Android project using gradle.
Like #Popeye did for maven, I added the following line to build.gradle, among dependencies:
testImplementation 'org.objenesis:objenesis:2.3'
That solved my problem.
I was getting the same error of:
java.lang.NoClassDefFoundError: org/objenesis/ObjenesisStd
when I was running a test in a new project that was using Mockito.
Turns out in addition to adding the Mockito Dependencies I also had to add the Objenesis dependency. All I need to do was add the below dependency to my pom.xml and it all worked perfectly fine.
<dependency>
<groupId>org.objenesis</groupId>
<artifactId>objenesis</artifactId>
<version>2.3</version>
<scope>test</scope>
</dependency>
I have this issue with the version of mockito-core 2.22.0.
After investigation it seems that the jar of objenesis was corrupted in my maven repository...
Just a rm -rf .m2/repository/org/objenesis is enough
I had the same problem, I deleted the mockito folder from my local repository and re-run the build, and it worked.
I am building an application using spring-boot (1.1.8.RELEASE), spring-data-neo4j (3.2.0.RELEASE) in order to connect to a stand alone neo4j server via rest api. I am using spring-test in order to test the application.
I would like to clean the database before running the unit test. I created a method cleanDb to be executed before to start the transaction. But I face a NullPointerException when cleanDb method from AppTests is run.
FYI when I removed this method all the unit-test pass.
Thank you for your help
Find below my spring configuration
#Configuration
#ComponentScan
#EnableTransactionManagement
#EnableAutoConfiguration
public class AppConfig extends Neo4jConfiguration {
public AppConfig() {
setBasePackage("demo");
}
#Bean
public GraphDatabaseService graphDatabaseService(Environment environment) {
return new SpringRestGraphDatabase("http://localhost:7474/db/data");
}
}
Find below my test class
#SuppressWarnings("deprecation")
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = AppConfig.class)
#Transactional
public class AppTests {
#Autowired
private Neo4jTemplate template;
#Rollback(false)
#BeforeTransaction
public void cleanDb() {
Neo4jHelper.cleanDb(template);
}
#Test
public void templateTest() {
Person person = new Person();
person.setName("Benoit");
person.setBorn(1986);
Person newPerson = template.save(person);
Person retrievedPerson = template.findOne(newPerson.getNodeId(),Person.class);
Assert.assertEquals("Benoit", retrievedPerson.getName());
}
}
Find below the Failure trace when I execute the unit test:
org.springframework.data.neo4j.core.UncategorizedGraphStoreException: Error cleaning database ; nested exception is java.lang.NullPointerException
at org.springframework.data.neo4j.support.node.Neo4jHelper.cleanDb(Neo4jHelper.java:78)
at org.springframework.data.neo4j.support.node.Neo4jHelper.cleanDb(Neo4jHelper.java:67)
at org.springframework.data.neo4j.support.node.Neo4jHelper.cleanDb(Neo4jHelper.java:38)
at demo.AppTests.cleanDb(AppTests.java:46)
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.springframework.test.context.transaction.TransactionalTestExecutionListener.runBeforeTransactionMethods(TransactionalTestExecutionListener.java:213)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.beforeTestMethod(TransactionalTestExecutionListener.java:167)
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:368)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
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:233)
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:176)
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: java.lang.NullPointerException
at org.neo4j.tooling.GlobalGraphOperations.assertInTransaction(GlobalGraphOperations.java:236)
at org.neo4j.tooling.GlobalGraphOperations.getAllNodes(GlobalGraphOperations.java:82)
at org.springframework.data.neo4j.support.node.Neo4jHelper.removeNodes(Neo4jHelper.java:88)
at org.springframework.data.neo4j.support.node.Neo4jHelper.cleanDb(Neo4jHelper.java:74)
... 30 more
)
Thanks
Regards
The rest-graph database is just a fake wrapper.
It doesn't support the methods cleanDB uses.
You can clean your database by running a Cypher statement like this:
MATCH (n)
OPTIONAL MATCH (n)-[r]-()
DELETE n,r
I m using grails 2.2, and i try to test a class with easymock.
My class is called Task, and contains a service called Service, that i would like to mock in my test.
void test(){
Task task = new Task()
Service service = createMock(Service.class)
task.service = service
expect(service.call(10)).andReturn(true)
replay(service)
task.execute()
}
And here is the code of the method call:
boolean call(Long id){}
But, systematically, when i run the test in my IDE or with the test-app command provided by grails), i have the following error:
java.lang.IllegalStateException: missing behavior definition for the preceding method call getMetaClass()
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:43)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:73)
at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:92)
at com.Service$$EnhancerByCGLIB$$fa4a7672.getMetaClass(<generated>)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.checkCall(PogoMetaClassSite.java:59)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:36)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at com.myApp.Test.test(MyTest.groovy:86)
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:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:22)
... 18 more
It seems i have an error in my test, but i can t see what i m doing wrong.
Can you help me ?