Spring Data Neo4j - Unit Test - cleandb NullPointerException - unit-testing

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

Related

"Failed to load ApplicationContext" error in during controller test and Inability to create bean

I try to write a test for my Controller but in first time , when I run my test , it not found my security configuration (see here) . I add security Configuration to test package as TestAppSecurityConfig class and use #ComponentScan on this class . But I think I've made it wrong Because I get "Failed to load ApplicationContext" error .
Do you know how to fix it?
ClassPath:
"main"
ir.fidar.seclab.security.config.AppSecurityConfig //real security config
ir.fidar.seclab.security.AppAuthenticationProvider
ir.fidar.seclab.security.AppUserDetails
ir.fidar.seclab.security.service.AppUserDetailsService
ir.fidar.seclab.service.impl.PrivilegeServiceImpl
"test"
ir.fidar.seclab.config.TestAppSecurityConfig
ir.fidar.seclab.controllersTest.AndroidGuardInfoControllerTest
TestAppSecurityConfig class :
#Configuration
#EnableWebSecurity
#ComponentScan(basePackages = {"ir.fidar.seclab"})
public class TestAppSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AppUserDetailsService appUserDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(getProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests()
.antMatchers("/users/**","/roles/**","/privileges/**").hasAuthority("manager")
.antMatchers("/android-guard-infos/**","process-queues/**",
"/risk-android-infos/**","/summery-infos/**",
"/virus-total-infos/**","/vt-process-queues/**").permitAll();
}
#Bean
public AppAuthenticationProvider getProvider(){
AppAuthenticationProvider provider = new AppAuthenticationProvider(appUserDetailsService);
return provider;
}
}
my dependency for test and security is :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
my test class:
#RunWith(SpringRunner.class)
#WebMvcTest(AndroidGuardInfoController.class)
#Import(TestAppSecurityConfig.class)
public class AndroidGuardInfoControllerTest {
#Autowired
private MockMvc mvc;
#MockBean
private AndroidGuardInfoService controller;
#Test
public void getOneTest() throws Exception {
AndroidGuardInfo data = new AndroidGuardInfo();
Mockito.when(controller.getOne(1L)).thenReturn(data);
mvc.perform(MockMvcRequestBuilders.get("/android-guard-infos/1")).andExpect(status().isOk());
}
}
and error:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.postProcessFields(MockitoTestExecutionListener.java:99)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.injectFields(MockitoTestExecutionListener.java:79)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:54)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
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: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'privilegeController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'privilegeServiceImpl': Unsatisfied dependency expressed through field 'repo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ir.fidar.seclab.dao.PrivilegeRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:139)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
... 25 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'privilegeServiceImpl': Unsatisfied dependency expressed through field 'repo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ir.fidar.seclab.dao.PrivilegeRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583)
... 43 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ir.fidar.seclab.dao.PrivilegeRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1506)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1101)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583)
... 56 more
This is because you have to enable repository scanning which is missing from your configuration.
e.g. If you are using JPA repositories than you have enable JPA repositories as follows,
#EnableJpaRepositories(basePackages = { "ir.fidar.seclab.dao" } )

java.lang.NoClassDefFoundError: org/objenesis/ObjenesisStd with Mockito

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.

unit test in grails: "missing behavior definition for the preceding method call getMetaClass()"

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 ?

PowerMock, Mockito and mocking final class from the reflection api

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.

Axis2 error when invoking web service from another web service

I have an Axis2 web service called DownloadServer that is invoking another Axis2 web service called Publisher. They are deployed on the same server. Here is the code for the two web services.
In class Publisher.java:
public String getFileServers(){
return "http://localhost:8080/axis2/services/FileServer1?wsdl http://localhost:8080/axis2/services/FileServer2?wsdl";
}
In class DownloadServer.java:
public synchronized String getBandwidth(String title) {
try {
// Call Publisher service to get addresses of File Servers
RPCServiceClient serviceClient = new RPCServiceClient();
Options options = serviceClient.getOptions();
EndpointReference targetEPR = new EndpointReference(
"http://localhost:8080/axis2/services/Publisher?wsdl");
options.setProperty(HTTPConstants.AUTO_RELEASE_CONNECTION,
org.apache.axis2.Constants.VALUE_TRUE);
options.setTo(targetEPR);
QName methodName = new QName("http://ws.apache.org/axis2",
"getFileServers");
Class[] returnTypes = new Class[] { String.class };
Object[] args = new Object[] {};
// Exception occurs on the next line
Object[] response = serviceClient.invokeBlocking(methodName, args,
returnTypes);
serviceClient.cleanupTransport();
String fileServers = (String) response[0];
return fileServers
} catch (Exception e) {
e.printStackTrace(out);
return "0";
}
}
I am getting the following Axis2 fault:
org.apache.axis2.AxisFault: The server did not recognise the action which it received:
at org.apache.axis2.handlers.addressing.AddressingInFaultHandler.invoke(AddressingInFaultHandler.java:114)
at org.apache.axis2.engine.Phase.invoke(Phase.java:318)
at org.apache.axis2.engine.AxisEngine.invoke(AxisEngine.java:254)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:160)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:364)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:417)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:540)
at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:521)
at org.apache.axis2.rpc.client.RPCServiceClient.invokeBlocking(RPCServiceClient.java:102)
at DownloadServer.getBandwidth(DownloadServer.java:56)
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.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:194)
at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:102)
at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:114)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:173)
at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:173)
at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:144)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
The interesting aspect is that when I run the DownloadServer class as a regular java application (not invoked as a web service), i do not get the same exception.
Does anyone have any idea what may be going wrong when the same code is executed as a web service?
OK, I found the answer eventually. Looks like explicitly setting the SOAP action solves the problem. It can be done like this:
options.setAction("urn:getFileServers");