java.lang.NoClassDefFoundError: org/objenesis/ObjenesisStd with Mockito - unit-testing

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.

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" } )

Spring Data Neo4j - Unit Test - cleandb NullPointerException

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

Unit testing CDI with CDI-Unit Jglue

we want to use Jglue framework for unit testing our CDI application. We use gradle for building.
We have prepared something like this:
1) Class to test:
#Default
public class RateTypeHibernateFactory implements RateTypeFactory {
#Override
public RateType getInstance(String name, String description) {
RateType rateType = getInstance();
rateType.setName(name);
rateType.setDescription(description);
return rateType;
}
}
2) Interface:
public interface RateTypeFactory {
public RateType getInstance(String name, String description);
}
3) Gradle settings (we followed getting started http://jglue.org/cdi-unit/)
dependencies {
testCompile (group: 'junit', name: 'junit', version: '4.8.2')
testCompile (group: 'org.jglue.cdi-unit', name: 'cdi-unit', version: '2.2.0')
}
4) Test class:
#RunWith(CdiRunner.class)
public class RateTypeFactoryTest {
#Inject RateTypeFactory rateTypeFactory;
#Test
public void testGetInstance() {
RateType rateType = rateTypeFactory.getInstance();
assertNotNull(rateType);
}
}
When we run this simple test, we always get this exception:
com.etnetera.projects.ticketing.model.factory.RateTypeFactoryTest > testGetInstance FAILED
java.lang.NoSuchMethodError
1 test completed, 1 failed
:test FAILED
In /build/reports/tests/index.html there is:
java.lang.NoSuchMethodError: org.jboss.weld.metadata.BeansXmlImpl.<init>(Ljava/util/List;Ljava/util/List;Ljava/util/List;Ljava/util/List;Lorg/jboss/weld/bootstrap/spi/Scanning;Ljava/net/URL;Lorg/jboss/weld/bootstrap/spi/BeanDiscoveryMode;Ljava/lang/String;)V
at org.jglue.cdiunit.internal.WeldTestUrlDeployment.<init>(WeldTestUrlDeployment.java:80)
at org.jglue.cdiunit.CdiRunner$1.createDeployment(CdiRunner.java:71)
at org.jboss.weld.environment.se.Weld.initialize(Weld.java:137)
at org.jglue.cdiunit.CdiRunner.createTest(CdiRunner.java:82)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:258)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:255)
at org.jglue.cdiunit.CdiRunner.methodBlock(CdiRunner.java:113)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:55)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:42)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:71)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:49)
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.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at $Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:103)
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.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:66)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Please does anybody know how to avoid this exception? I can add some more details if needed.
This is usually caused by an unsupported version of weld being used.
However, I have just released CDI-Unit 2.2.1 which fixes a couple of issues with Gradle builds.
Please can you give it a go?
I have encountered a similar problem (with an error message a bit different). I googled a lot around this problem but did not found much about this, so I concluded that it was specific to my project. This lead me to suspect a version mismatch between the dependencies of the project.
I was using weld-servlet: 2.4.0.Final as a compile dependency and cdi-unit: 3.1.4 as a test dependency. And I noticed that cdi-unit had a dependency on weld-se-core: 2.3.2.Final. So I added weld-se-core to my dependency management with the same version as my weld-servlet artifact and it solved the problem.
For further reference, here is an extract of my pom.xml file
<properties>
<weld.version>2.4.0.Final</weld.version>
<cdi-unit.version>3.1.4</cdi-unit.version>
(...)
</properties>
<dependencyManagement>
<dependencies>
<!-- CDI -->
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet</artifactId>
<version>${weld.version}</version>
</dependency>
<!-- Tests -->
<dependency>
<groupId>org.jglue.cdi-unit</groupId>
<artifactId>cdi-unit</artifactId>
<version>${cdi-unit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>${weld.version}</version>
<scope>test</scope>
</dependency>
(...)
</dependencies>
</dependencyManagement>
<dependencies>
<!-- CDI -->
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet</artifactId>
</dependency>
<!-- Tests -->
<dependency>
<groupId>org.jglue.cdi-unit</groupId>
<artifactId>cdi-unit</artifactId>
</dependency>
(...)
</dependencies>
It seems you are invoking a method on the interface without the parameters.
Instead of
RateType rateType = rateTypeFactory.getInstance();
you should probably call
RateType rateType = rateTypeFactory.getInstance("name", "description");
Maybe I missed something gradle-related?

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.

Injecting logger, weld

I am trying to replace standard logger initialization by some injection
1-st.
I was trying to use weld weld logging in stateless bean/webservices
#Stateless
#WebService
public class EchoSSL {
#Inject
private Logger log;
public EchoSSL() {
}
public String echo(String msg) {
log.debug("Log test");
return "Echoing: " + msg;
}
}
But it not working for me.. i get java.lang.reflect.InvocationTargetException
javax.servlet.ServletException:
java.lang.reflect.InvocationTargetException
at
org.glassfish.webservices.monitoring.WebServiceTesterServlet.doPost(WebServiceTesterServlet.java:326)
at
org.glassfish.webservices.monitoring.WebServiceTesterServlet.invoke(WebServiceTesterServlet.java:102)
at
org.glassfish.webservices.EjbWebServiceServlet.service(EjbWebServiceServlet.java:110)
at
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at
com.sun.grizzly.http.servlet.FilterChainImpl.doFilter(FilterChainImpl.java:195)
at
com.sun.grizzly.http.servlet.FilterChainImpl.invokeFilterChain(FilterChainImpl.java:139)
at
com.sun.grizzly.http.servlet.ServletAdapter.doService(ServletAdapter.java:376)
at
com.sun.grizzly.http.servlet.ServletAdapter.service(ServletAdapter.java:329)
at
com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:166)
at
com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:100)
at
com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:245)
at
com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at
com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at
com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at
com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at
com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at
com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at
com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at
com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at
com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at
com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at
com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at
java.lang.Thread.run(Thread.java:619)
Caused by:
java.lang.reflect.InvocationTargetException
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.glassfish.webservices.monitoring.WebServiceTesterServlet.doPost(WebServiceTesterServlet.java:297)
... 24 more Caused by:
javax.xml.ws.soap.SOAPFaultException:
javax.ejb.EJBException at
com.sun.xml.ws.fault.SOAP11Fault.getProtocolException(SOAP11Fault.java:189)
at
com.sun.xml.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:130)
at
com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:119)
at
com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:89)
at
com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:140)
at $Proxy484.sayHello(Unknown Source)
... 29 more Caused by:
javax.ejb.EJBException at
com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5070)
at
com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:4968)
at
com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4756)
at
com.sun.ejb.containers.WebServiceInvocationHandler.invoke(WebServiceInvocationHandler.java:200)
at $Proxy464.sayHello(Unknown Source)
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.glassfish.webservices.InvokerImpl.invoke(InvokerImpl.java:78)
at
org.glassfish.webservices.EjbInvokerImpl.invoke(EjbInvokerImpl.java:78)
at
com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:146)
at
com.sun.xml.ws.server.sei.EndpointMethodHandler.invoke(EndpointMethodHandler.java:257)
at
com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:95)
at
com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:629)
at
com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:588)
at
com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:573)
at
com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:470)
at
com.sun.xml.ws.api.pipe.helper.AbstractTubeImpl.process(AbstractTubeImpl.java:112)
at
org.glassfish.webservices.MonitoringPipe.process(MonitoringPipe.java:138)
at
com.sun.xml.ws.api.pipe.helper.PipeAdapter.processRequest(PipeAdapter.java:115)
at
com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:629)
at
com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:588)
at
com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:573)
at
com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:470)
at
com.sun.xml.ws.api.pipe.helper.AbstractTubeImpl.process(AbstractTubeImpl.java:112)
at
com.sun.xml.ws.tx.service.TxServerPipe.process(TxServerPipe.java:306)
at
com.sun.xml.ws.api.pipe.helper.PipeAdapter.processRequest(PipeAdapter.java:115)
at
com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:629)
at
com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:588)
at
com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:573)
at
com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:470)
at
com.sun.xml.ws.api.pipe.helper.AbstractTubeImpl.process(AbstractTubeImpl.java:112)
at
com.sun.enterprise.security.webservices.CommonServerSecurityPipe.processRequest(CommonServerSecurityPipe.java:195)
at
com.sun.enterprise.security.webservices.CommonServerSecurityPipe.process(CommonServerSecurityPipe.java:127)
at
com.sun.xml.ws.api.pipe.helper.PipeAdapter.processRequest(PipeAdapter.java:115)
at
com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:629)
at
com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:588)
at
com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:573)
at
com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:470)
at
com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:295)
at
com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:519)
at
com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:288)
at
com.sun.xml.ws.transport.http.servlet.ServletAdapter.handle(ServletAdapter.java:143)
at
org.glassfish.webservices.Ejb3MessageDispatcher.handlePost(Ejb3MessageDispatcher.java:116)
at
org.glassfish.webservices.Ejb3MessageDispatcher.invoke(Ejb3MessageDispatcher.java:87)
at
org.glassfish.webservices.EjbWebServiceServlet.dispatchToEjbEndpoint(EjbWebServiceServlet.java:196)
at
org.glassfish.webservices.EjbWebServiceServlet.service(EjbWebServiceServlet.java:127)
... 22 more Caused by:
java.lang.NullPointerException at
ua.eset.inferno.heresy.ws.security.Hello.sayHello(Hello.java:33)
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.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1056)
at
org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1128)
at
com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5243)
at
com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:615)
at
com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797)
at
com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:567)
at
com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:157)
at
com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:139)
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
com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:858)
at
com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797)
at
com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:367)
at
com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5215)
at
com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5203)
at
com.sun.ejb.containers.WebServiceInvocationHandler.invoke(WebServiceInvocationHandler.java:188)
... 66 more
What is missed ?
2-nd
than I try this tutorial that is referenced to this - Custom Injections
But it also dosen`t help.
maven dependencies -
<dependencies>
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-logger</artifactId>
<version>1.0.0-CR2</version>
</dependency>
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-extensions</artifactId>
<version>1.0.0.Alpha1</version>
</dependency>
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-api</artifactId>
<version>1.0-CR2</version>
</dependency>
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core</artifactId>
<version>1.0.1-CR2</version>
</dependency>
</dependencies>
Q1: What is the rule of weld Logger injection in ejb / web services ?
Q2: Could it be wsdl/EJB/WebService issue ?
This is my approach:
Add the following dependencies to the pom.xml:
<!-- SL4J API -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.0</version>
</dependency>
<!-- SLF4J JDK14 Binding -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.6.0</version>
</dependency>
<!-- Injectable Weld-Logger -->
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-logger</artifactId>
<version>1.0.0-CR2</version>
</dependency>
Inject the Logger and use it as usual:
import javax.inject.Inject;
import org.slf4j.Logger;
public class Example {
#Inject
private Logger logger;
public void exampleFunc() {
logger.info("Hello Logger!");
}
}
If you wanna use Log4J instead of the SLF4J-JDK14-binding, i found this page. I tried it, but i couldn't get it to work so i still stick with my own solution.
Make sure your bean is in a bean archive - i.e. that you have META-INF/beans.xml
Apart from the weld extension, which I can't help you with unless you give the whole exception, you can create a producer that #Produces a Logger
The default slf4j logger producer is defined in Weld Extensions. You can see how the producer is written here if you wanted to wire up your own without including all of Weld Extensions.
in this case I haven`t placed bean.xml in META-INF.