如何将@Named bean注入Junit测试

前端之家收集整理的这篇文章主要介绍了如何将@Named bean注入Junit测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将@Named bean注入Junit测试.

这适用于我的ejb模块,但我的war模块中的相同方法失败了.
我想知道为什么我得到org.apache.openejb.OpenEJBException:创建应用程序失败:无法启动owb上下文.

我知道这与Issue with EJB 3.1 injected with CDI bean while running JUnit中的问题相同,但它不能与其他模块中的相同.

代码在这里:https://github.com/Crydust/guestbook

工作测试:guestbook / guestbook-ejb / src / test / java / be / crydust / guestbook / ejb / PostBoundaryTest.java

测试失败:guestbook / guestbook-web / src / test / java / be / crydust / guestbook / web / PostBackingTest.java

失败测试的来源(省略进口):

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())));
    }
}

测试失败的日志:

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: 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,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,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,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,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

解决方法

我使用针框架进行这类测试.它会自动注入可以按常规方式配置的模拟,但也可以用于在需要时注入实例(用于协作/集成测试).

你可以在这里找到它:http://needle.spree.de/

原文链接:https://www.f2er.com/java/128680.html

猜你在找的Java相关文章