Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a @Named bean into a Junit test

I'm trying to inject a @Named bean into a Junit test.

This works in my ejb module, but the same approach in my war module fails. I'd like to know why I get org.apache.openejb.OpenEJBException: Creating application failed: couldn't start owb context.

I know this looks like the same issue as in Issue with EJB 3.1 injected with CDI bean while running JUnit, but it can't be the same as it works in another module.

The source code is here: https://github.com/Crydust/guestbook

Working test: guestbook/guestbook-ejb/src/test/java/be/crydust/guestbook/ejb/PostBoundaryTest.java

Failing test: guestbook/guestbook-web/src/test/java/be/crydust/guestbook/web/PostBackingTest.java

Source of failing test (imports ommitted):

public class PostBackingTest {

    private static EJBContainer ejbContainer;

    @Inject
    PostBacking cut;

    @BeforeClass
    public static void startTheContainer() {
        ejbContainer = EJBContainer.createEJBContainer();
    }

    @Before
    public void setUp() throws Exception {
        ejbContainer.getContext().bind("inject", this);
    }

    @AfterClass
    public static void afterClass() {
        if (ejbContainer != null) {
            ejbContainer.close();
        }
    }

    // FIXME injection fails

    @Test
    public void testInjected() {
        assertThat(cut, is(not(nullValue())));
    }
}

Log of failing test:

cd D:\home\kristof\Projects\guestbook\guestbook-web; JAVA_HOME=C:\\opt\\Java\\jdk1.7.0_45 cmd /c "\"\"C:\\opt\\NetBeans 7.4\\java\\maven\\bin\\mvn.bat\" -Dmaven.ext.class.path=\"C:\\opt\\NetBeans 7.4\\java\\maven-nblib\\netbeans-eventspy.jar\" test\""
Scanning for projects...

------------------------------------------------------------------------
Building guestbook-web 1.0-SNAPSHOT
------------------------------------------------------------------------

--- jacoco-maven-plugin:0.6.3.201306030806:prepare-agent (prepare-agent) @ guestbook-web ---
surefireArgLine set to -javaagent:D:\home\kristof\.m2\repository\org\jacoco\org.jacoco.agent\0.6.3.201306030806\org.jacoco.agent-0.6.3.201306030806-runtime.jar=destfile=D:\home\kristof\Projects\guestbook\guestbook-web\target\jacoco.exec 

--- maven-resources-plugin:2.5:resources (default-resources) @ guestbook-web ---
[debug] execute contextualize
Using 'UTF-8' encoding to copy filtered resources.
Copying 1 resource

--- maven-dependency-plugin:2.8:copy (copy) @ guestbook-web ---
Configured Artifact: org.apache.openejb:openejb-javaagent:4.6.0:jar
org.apache.openejb:openejb-javaagent:4.6.0:jar already exists in D:\home\kristof\Projects\guestbook\guestbook-web\target

--- maven-compiler-plugin:3.1:compile (default-compile) @ guestbook-web ---
Nothing to compile - all classes are up to date

--- maven-resources-plugin:2.5:testResources (default-testResources) @ guestbook-web ---
[debug] execute contextualize
Using 'UTF-8' encoding to copy filtered resources.
skip non existing resourceDirectory D:\home\kristof\Projects\guestbook\guestbook-web\src\test\resources

--- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ guestbook-web ---
Nothing to compile - all classes are up to date

--- maven-surefire-plugin:2.16:test (default-test) @ guestbook-web ---
Surefire report directory: D:\home\kristof\Projects\guestbook\guestbook-web\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
98  classpath-bootstrap  INFO   [main] openjpa.Runtime - OpenJPA dynamically loaded a validation provider.
Running be.crydust.guestbook.web.PostBackingTest
dec 17, 2013 12:16:48 PM org.apache.openejb.OpenEJB$Instance <init>
INFO: ********************************************************************************
dec 17, 2013 12:16:48 PM org.apache.openejb.OpenEJB$Instance <init>
INFO: OpenEJB http://openejb.apache.org/
dec 17, 2013 12:16:48 PM org.apache.openejb.OpenEJB$Instance <init>
INFO: Startup: Tue Dec 17 12:16:48 CET 2013
dec 17, 2013 12:16:48 PM org.apache.openejb.OpenEJB$Instance <init>
INFO: Copyright 1999-2013 (C) Apache OpenEJB Project, All Rights Reserved.
dec 17, 2013 12:16:48 PM org.apache.openejb.OpenEJB$Instance <init>
INFO: Version: 4.6.0
dec 17, 2013 12:16:48 PM org.apache.openejb.OpenEJB$Instance <init>
INFO: Build date: 20131117
dec 17, 2013 12:16:48 PM org.apache.openejb.OpenEJB$Instance <init>
INFO: Build time: 06:49
dec 17, 2013 12:16:48 PM org.apache.openejb.OpenEJB$Instance <init>
INFO: ********************************************************************************
dec 17, 2013 12:16:48 PM org.apache.openejb.OpenEJB$Instance <init>
INFO: openejb.home = D:\home\kristof\Projects\guestbook\guestbook-web\target
dec 17, 2013 12:16:48 PM org.apache.openejb.OpenEJB$Instance <init>
INFO: openejb.base = D:\home\kristof\Projects\guestbook\guestbook-web\target
dec 17, 2013 12:16:48 PM org.apache.openejb.cdi.CdiBuilder initializeOWB
INFO: Created new singletonService org.apache.openejb.cdi.ThreadSingletonServiceImpl@31185f32
dec 17, 2013 12:16:48 PM org.apache.openejb.cdi.CdiBuilder initializeOWB
INFO: Succeeded in installing singleton service
dec 17, 2013 12:16:48 PM org.apache.openejb.util.OptionsLog info
INFO: Using 'javax.ejb.embeddable.EJBContainer=true'
dec 17, 2013 12:16:48 PM org.apache.openejb.config.ConfigUtils searchForConfiguration
INFO: Cannot find the configuration file [conf/openejb.xml].  Will attempt to create one for the beans deployed.
dec 17, 2013 12:16:48 PM org.apache.openejb.config.ConfigurationFactory configureService
INFO: Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)
dec 17, 2013 12:16:48 PM org.apache.openejb.config.ConfigurationFactory configureService
INFO: Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)
dec 17, 2013 12:16:48 PM org.apache.openejb.assembler.classic.Assembler createRecipe
INFO: Creating TransactionManager(id=Default Transaction Manager)
dec 17, 2013 12:16:48 PM org.apache.openejb.assembler.classic.Assembler createRecipe
INFO: Creating SecurityService(id=Default Security Service)
dec 17, 2013 12:16:48 PM org.apache.openejb.config.DeploymentsResolver processUrls
INFO: Found PersistenceModule in classpath: d:\home\kristof\.m2\repository\be\crydust\guestbook-entities\1.0-snapshot\guestbook-entities-1.0-snapshot.jar
dec 17, 2013 12:16:49 PM org.apache.openejb.config.DeploymentsResolver processUrls
INFO: Found EjbModule in classpath: d:\home\kristof\.m2\repository\be\crydust\guestbook-ejb\1.0-snapshot\guestbook-ejb-1.0-snapshot.jar
dec 17, 2013 12:16:49 PM org.apache.openejb.config.ConfigurationFactory loadApplication
INFO: Beginning load: d:\home\kristof\.m2\repository\be\crydust\guestbook-entities\1.0-snapshot\guestbook-entities-1.0-snapshot.jar
dec 17, 2013 12:16:49 PM org.apache.openejb.config.ConfigurationFactory loadApplication
INFO: Beginning load: d:\home\kristof\.m2\repository\be\crydust\guestbook-ejb\1.0-snapshot\guestbook-ejb-1.0-snapshot.jar
dec 17, 2013 12:16:49 PM org.apache.openejb.config.ConfigurationFactory configureApplication
INFO: Configuring enterprise application: D:\home\kristof\Projects\guestbook\guestbook-web\target
dec 17, 2013 12:16:49 PM org.apache.openejb.config.InitEjbDeployments deploy
INFO: Auto-deploying ejb PostBoundary: EjbDeployment(deployment-id=PostBoundary)
dec 17, 2013 12:16:49 PM org.apache.openejb.config.ConfigurationFactory configureService
INFO: Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)
dec 17, 2013 12:16:49 PM org.apache.openejb.config.AutoConfig createContainer
INFO: Auto-creating a container for bean guestbook-ejb-1.0-SNAPSHOT.Comp577600423: Container(type=MANAGED, id=Default Managed Container)
dec 17, 2013 12:16:49 PM org.apache.openejb.assembler.classic.Assembler createRecipe
INFO: Creating Container(id=Default Managed Container)
dec 17, 2013 12:16:49 PM org.apache.openejb.core.managed.SimplePassivater init
INFO: Using directory C:\Users\kristof\AppData\Local\Temp for stateful session passivation
dec 17, 2013 12:16:49 PM org.apache.openejb.config.ConfigurationFactory configureService
INFO: Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)
dec 17, 2013 12:16:49 PM org.apache.openejb.config.AutoConfig createContainer
INFO: Auto-creating a container for bean PostBoundary: Container(type=STATELESS, id=Default Stateless Container)
dec 17, 2013 12:16:49 PM org.apache.openejb.assembler.classic.Assembler createRecipe
INFO: Creating Container(id=Default Stateless Container)
dec 17, 2013 12:16:49 PM org.apache.openejb.config.AutoConfig deploy
INFO: Configuring PersistenceUnit(name=guestbookPU)
dec 17, 2013 12:16:49 PM org.apache.openejb.config.ConfigurationFactory configureService
INFO: Configuring Service(id=Default JDBC Database, type=Resource, provider-id=Default JDBC Database)
dec 17, 2013 12:16:49 PM org.apache.openejb.config.AutoConfig logAutoCreateResource
INFO: Auto-creating a Resource with id 'Default JDBC Database' of type 'DataSource for 'guestbookPU'.
dec 17, 2013 12:16:49 PM org.apache.openejb.assembler.classic.Assembler createRecipe
INFO: Creating Resource(id=Default JDBC Database)
dec 17, 2013 12:16:49 PM org.apache.openejb.config.ConfigurationFactory configureService
INFO: Configuring Service(id=Default Unmanaged JDBC Database, type=Resource, provider-id=Default Unmanaged JDBC Database)
dec 17, 2013 12:16:49 PM org.apache.openejb.config.AutoConfig logAutoCreateResource
INFO: Auto-creating a Resource with id 'Default Unmanaged JDBC Database' of type 'DataSource for 'guestbookPU'.
dec 17, 2013 12:16:49 PM org.apache.openejb.assembler.classic.Assembler createRecipe
INFO: Creating Resource(id=Default Unmanaged JDBC Database)
dec 17, 2013 12:16:49 PM org.apache.openejb.config.AutoConfig setJtaDataSource
INFO: Adjusting PersistenceUnit guestbookPU <jta-data-source> to Resource ID 'Default JDBC Database' from 'null'
dec 17, 2013 12:16:49 PM org.apache.openejb.config.AutoConfig setNonJtaDataSource
INFO: Adjusting PersistenceUnit guestbookPU <non-jta-data-source> to Resource ID 'Default Unmanaged JDBC Database' from 'null'
dec 17, 2013 12:16:49 PM org.apache.openejb.config.AppInfoBuilder build
INFO: Enterprise application "D:\home\kristof\Projects\guestbook\guestbook-web\target" loaded.
dec 17, 2013 12:16:49 PM org.apache.openejb.assembler.classic.Assembler createApplication
INFO: Assembling app: D:\home\kristof\Projects\guestbook\guestbook-web\target
dec 17, 2013 12:16:49 PM null
INFO: OpenJPA dynamically loaded a validation provider.
dec 17, 2013 12:16:49 PM org.apache.openejb.assembler.classic.ReloadableEntityManagerFactory createDelegate
INFO: PersistenceUnit(name=guestbookPU, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 12ms
dec 17, 2013 12:16:49 PM org.apache.openejb.assembler.classic.JndiBuilder bindJava
INFO: Jndi(name="java:global/guestbook-ejb-1.0-SNAPSHOT/PostBoundary!be.crydust.guestbook.ejb.PostBoundary")
dec 17, 2013 12:16:49 PM org.apache.openejb.assembler.classic.JndiBuilder bindJava
INFO: Jndi(name="java:global/guestbook-ejb-1.0-SNAPSHOT/PostBoundary")
dec 17, 2013 12:16:49 PM org.apache.openejb.cdi.CdiBuilder initSingleton
INFO: Existing thread singleton service in SystemInstance(): org.apache.openejb.cdi.ThreadSingletonServiceImpl@31185f32
dec 17, 2013 12:16:49 PM org.apache.openejb.cdi.OpenEJBLifecycle startApplication
INFO: OpenWebBeans Container is starting...
dec 17, 2013 12:16:49 PM org.apache.webbeans.plugins.PluginLoader startUp
INFO: Adding OpenWebBeansPlugin : [CdiPlugin]
dec 17, 2013 12:16:49 PM org.apache.openejb.cdi.OpenEJBLifecycle startApplication
SEVERE: CDI Beans module deployment failed
org.apache.webbeans.exception.inject.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Api type [be.crydust.guestbook.web.PostBacking] is not found with the qualifiers 
Qualifiers: [@javax.enterprise.inject.Default()]
for injection into Field Injection Point, field name :  cut, Bean Owner : [PostBackingTest, Name:null, WebBeans Type:ENTERPRISE, API Types:[be.crydust.guestbook.web.PostBackingTest,java.lang.Object,java.io.Serializable], Qualifiers:[javax.enterprise.inject.Default,javax.enterprise.inject.Any]]
    at org.apache.webbeans.config.BeansDeployer.deploy(BeansDeployer.java:213)
    at org.apache.openejb.cdi.OpenEJBLifecycle.startApplication(OpenEJBLifecycle.java:187)
    at org.apache.openejb.cdi.ThreadSingletonServiceImpl.initialize(ThreadSingletonServiceImpl.java:162)
    at org.apache.openejb.cdi.CdiBuilder.build(CdiBuilder.java:43)
    at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:799)
    at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:612)
    at org.apache.openejb.OpenEjbContainer$Provider.createEJBContainer(OpenEjbContainer.java:415)
    at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:56)
    at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:43)
    at be.crydust.guestbook.web.PostBackingTest.startTheContainer(PostBackingTest.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Api type [be.crydust.guestbook.web.PostBacking] is not found with the qualifiers 
Qualifiers: [@javax.enterprise.inject.Default()]
for injection into Field Injection Point, field name :  cut, Bean Owner : [PostBackingTest, Name:null, WebBeans Type:ENTERPRISE, API Types:[be.crydust.guestbook.web.PostBackingTest,java.lang.Object,java.io.Serializable], Qualifiers:[javax.enterprise.inject.Default,javax.enterprise.inject.Any]]
    at org.apache.webbeans.util.InjectionExceptionUtil.throwUnsatisfiedResolutionException(InjectionExceptionUtil.java:60)
    at org.apache.webbeans.container.InjectionResolver.checkInjectionPoint(InjectionResolver.java:195)
    at org.apache.webbeans.container.BeanManagerImpl.validate(BeanManagerImpl.java:954)
    at org.apache.webbeans.config.BeansDeployer.validate(BeansDeployer.java:470)
    at org.apache.webbeans.config.BeansDeployer.validateInjectionPoints(BeansDeployer.java:420)
    at org.apache.webbeans.config.BeansDeployer.deploy(BeansDeployer.java:200)
    ... 25 more

dec 17, 2013 12:16:49 PM org.apache.openejb.assembler.classic.Assembler destroyApplication
INFO: Undeploying app: D:\home\kristof\Projects\guestbook\guestbook-web\target
dec 17, 2013 12:16:49 PM org.apache.openejb.assembler.classic.Assembler destroyResource
INFO: Closing DataSource: Default JDBC Database
dec 17, 2013 12:16:49 PM org.apache.openejb.assembler.classic.Assembler destroyResource
INFO: Closing DataSource: Default Unmanaged JDBC Database
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.458 sec <<< FAILURE! - in be.crydust.guestbook.web.PostBackingTest
be.crydust.guestbook.web.PostBackingTest  Time elapsed: 1.458 sec  <<< ERROR!
org.apache.openejb.OpenEjbContainer$AssembleApplicationException: org.apache.openejb.OpenEJBException: Creating application failed: D:\home\kristof\Projects\guestbook\guestbook-web\target: couldn't start owb context
    at org.apache.webbeans.util.InjectionExceptionUtil.throwUnsatisfiedResolutionException(InjectionExceptionUtil.java:60)
    at org.apache.webbeans.container.InjectionResolver.checkInjectionPoint(InjectionResolver.java:195)
    at org.apache.webbeans.container.BeanManagerImpl.validate(BeanManagerImpl.java:954)
    at org.apache.webbeans.config.BeansDeployer.validate(BeansDeployer.java:470)
    at org.apache.webbeans.config.BeansDeployer.validateInjectionPoints(BeansDeployer.java:420)
    at org.apache.webbeans.config.BeansDeployer.deploy(BeansDeployer.java:200)
    at org.apache.openejb.cdi.OpenEJBLifecycle.startApplication(OpenEJBLifecycle.java:187)
    at org.apache.openejb.cdi.ThreadSingletonServiceImpl.initialize(ThreadSingletonServiceImpl.java:162)
    at org.apache.openejb.cdi.CdiBuilder.build(CdiBuilder.java:43)
    at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:799)
    at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:612)
    at org.apache.openejb.OpenEjbContainer$Provider.createEJBContainer(OpenEjbContainer.java:415)
    at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:56)
    at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:43)
    at be.crydust.guestbook.web.PostBackingTest.startTheContainer(PostBackingTest.java:31)


Results :

Tests in error: 
  PostBackingTest.startTheContainer:31 » AssembleApplication org.apache.openejb....

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0

------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 4.595s
Finished at: Tue Dec 17 12:16:49 CET 2013
Final Memory: 17M/224M
------------------------------------------------------------------------
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.16:test (default-test) on project guestbook-web: There are test failures.

Please refer to D:\home\kristof\Projects\guestbook\guestbook-web\target\surefire-reports for the individual test results.
-> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
like image 285
Kristof Neirynck Avatar asked Dec 17 '13 11:12

Kristof Neirynck


People also ask

Can I use Autowired in JUnit?

Also note that we can wire other spring beans in our jUnit test classes using @Autowired annotation.

Can we use Autowired in test class?

To check the Service class, we need to have an instance of the Service class created and available as a @Bean so that we can @Autowire it in our test class. We can achieve this configuration using the @TestConfiguration annotation.

What is dependency injection in JUnit?

Dependency injection in JUnit 5ParameterResolver defines the API for test extensions that wish to dynamically resolve parameters at runtime. If a test class constructor, a test method, or a lifecycle method accepts a parameter, the parameter must be resolved at runtime by a registered ParameterResolver .


2 Answers

I use the needle framework for these kind of tests. It automatically injects mocks that you can configure the usual way, but also can be used to inject real instances if needed (for collaboration/integration testing).

You can find it here: http://needle.spree.de/

like image 173
Jan Galinski Avatar answered Oct 14 '22 03:10

Jan Galinski


I believe OpenEJB expects the beans.xml in META-INF folder, although the war should have it it in the WEB-INF folder. Can you verify this by creating a empty beans.xml in test/resources/META-INF folder?

like image 24
apurohit Avatar answered Oct 14 '22 02:10

apurohit