CDI + JUnit = demoiselle-junit

12jan11

Demoiselle + CDI + JUnit

Dedico este post a todos que precisam de um mero @Inject nos seus casos de teste e não acham nenhuma solução simples pela Web. Faz tempo que passamos por este aperto no projeto Demoiselle 2.0. Esperamos durante meses por uma versão estável do Arquillian, que ainda não saiu e nem é tão fácil de usar. Queríamos algo simples, sem recursos super-avançados, que se aplicasse na maioria dos casos. Então criamos a extensão demoiselle-junit.

O projeto Arquillian sem sombra de dúvidas é um grande projeto, talvez muito grande para quem quer resolver problemas simples de injeção de beans nos seus casos de teste. Criamos a demoiselle-junit, uma extensão do Framework Demoiselle 2.0, que não pretende competir com o Arquillian. Na realidade trata-se de uma alternativa simples para casos do dia-a-dia, algo prático do tipo plugar-e-usar.

Esta extensão estará disponível à partir da versão 2.0.1 do framework, mas, caso você tenha interesse em experimentar ou propor melhorias, segue o passo-a-passo da configuração da versão 2.1.0 usando o Maven. Adicione o seguinte repositório:

<repositories>
	<repository>
		<id>demoiselle.sourceforge.net</id>
		<name>Demoiselle Maven Repository</name>
		<url>http://demoiselle.sourceforge.net/repository/snapshot</url>
	</repository>
</repositories>

Adicione a seguinte dependência:

<dependency>
	<groupId>br.gov.frameworkdemoiselle</groupId>
	<artifactId>demoiselle-junit</artifactId>
	<version>2.1.0</version>
	<scope>test</scope>
</dependency>

Agora faça sua classe de teste conforme o seguinte exemplo:

@RunWith(DemoiselleRunner.class)
public class MeuTest {

	@Inject
	private MeuBean bean;

	@Test
	public void algumTeste() {
		Assert.assertNotNull(bean);
	}
}

Agora a injeção vai funcionar perfeitamente. Basicamente, levantamos um ambiente CDI com ajuda do Weld-SE. Boa diversão! 😉

Anúncios


3 Responses to “CDI + JUnit = demoiselle-junit”

  1. 1 Rudolfo Borges

    Não funciona em um projeto jsf-jpa? Criei um projeto demoiselle-jsf-jpa e seguir esses passos mas quando realizar meus testes dá erro.

    org.jboss.weld.exceptions.DeploymentException: Exception List with 1 exceptions:
    Exception 0 :
    org.jboss.weld.exceptions.WeldException: WELD-000049 Unable to invoke [method] @PostConstruct public br.gov.frameworkdemoiselle.internal.producer.EntityManagerProducer.init() on br.gov.frameworkdemoiselle.internal.producer.EntityManagerProducer@455dd32a
    at org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:595)
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.postConstruct(ManagedBean.java:200)
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:340)
    at br.gov.frameworkdemoiselle.internal.context.ThreadLocalContext.get(ThreadLocalContext.java:95)
    at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:99)
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:87)
    at br.gov.frameworkdemoiselle.internal.producer.org$jboss$weld$bean-classpath-ManagedBean-class_br$gov$frameworkdemoiselle$internal$producer$EntityManagerProducer_$$_WeldClientProxy.getCache(org$jboss$weld$bean-classpath-ManagedBean-class_br$gov$frameworkdemoiselle$internal$producer$EntityManagerProducer_$$_WeldClientProxy.java)
    at br.gov.frameworkdemoiselle.transaction.JPATransaction.getDelegate(JPATransaction.java:65)
    at br.gov.frameworkdemoiselle.transaction.JPATransaction.isActive(JPATransaction.java:120)
    at br.gov.frameworkdemoiselle.transaction.org$jboss$weld$bean-classpath-ManagedBean-class_br$gov$frameworkdemoiselle$transaction$JPATransaction_$$_WeldClientProxy.isActive(org$jboss$weld$bean-classpath-ManagedBean-class_br$gov$frameworkdemoiselle$transaction$JPATransaction_$$_WeldClientProxy.java)
    at br.gov.frameworkdemoiselle.internal.interceptor.TransactionInterceptor.initiate(TransactionInterceptor.java:104)
    at br.gov.frameworkdemoiselle.internal.interceptor.TransactionInterceptor.manage(TransactionInterceptor.java:82)
    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.jboss.interceptor.proxy.InterceptorInvocation$InterceptorMethodInvocation.invoke(InterceptorInvocation.java:72)
    at org.jboss.interceptor.proxy.SimpleInterceptionChain.invokeNextInterceptor(SimpleInterceptionChain.java:82)
    at org.jboss.interceptor.proxy.InterceptorInvocationContext.proceed(InterceptorInvocationContext.java:143)
    at br.gov.frameworkdemoiselle.internal.interceptor.ExceptionHandlerInterceptor.manage(ExceptionHandlerInterceptor.java:167)
    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.jboss.interceptor.proxy.InterceptorInvocation$InterceptorMethodInvocation.invoke(InterceptorInvocation.java:72)
    at org.jboss.interceptor.proxy.SimpleInterceptionChain.invokeNextInterceptor(SimpleInterceptionChain.java:82)
    at org.jboss.interceptor.proxy.InterceptorMethodHandler.executeInterception(InterceptorMethodHandler.java:133)
    at org.jboss.interceptor.proxy.InterceptorMethodHandler.invoke(InterceptorMethodHandler.java:112)
    at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:65)
    at agora.foi.business.org$jboss$weld$bean-classpath-ManagedBean-class_agora$foi$business$BookmarkBC_$$_WeldSubclass.load(org$jboss$weld$bean-classpath-ManagedBean-class_agora$foi$business$BookmarkBC_$$_WeldSubclass.java)
    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 br.gov.frameworkdemoiselle.internal.processor.AnnotatedMethodProcessor.process(AnnotatedMethodProcessor.java:67)
    at br.gov.frameworkdemoiselle.internal.bootstrap.StartupBootstrap.startup(StartupBootstrap.java:116)
    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.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:305)
    at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:54)
    at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:163)
    at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:299)
    at org.jboss.weld.introspector.jlr.WeldMethodImpl.invokeOnInstance(WeldMethodImpl.java:188)
    at org.jboss.weld.introspector.ForwardingWeldMethod.invokeOnInstance(ForwardingWeldMethod.java:59)
    at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:198)
    at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:270)
    at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:253)
    at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:222)
    at org.jboss.weld.bootstrap.events.AbstractContainerEvent.fire(AbstractContainerEvent.java:88)
    at org.jboss.weld.bootstrap.events.AbstractDeploymentContainerEvent.fire(AbstractDeploymentContainerEvent.java:52)
    at org.jboss.weld.bootstrap.events.AfterDeploymentValidationImpl.fire(AfterDeploymentValidationImpl.java:34)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:393)
    at org.jboss.weld.environment.se.Weld.initialize(Weld.java:88)
    at org.jboss.weld.environment.se.StartMain.go(StartMain.java:45)
    at org.jboss.weld.environment.se.StartMain.main(StartMain.java:57)
    at br.gov.frameworkdemoiselle.util.DemoiselleRunner.init(DemoiselleRunner.java:56)
    at br.gov.frameworkdemoiselle.util.DemoiselleRunner.(DemoiselleRunner.java:50)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.(JUnit4TestReference.java:32)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.(JUnit4TestClassReference.java:25)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:41)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:31)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    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.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.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:305)
    at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:54)
    at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:163)
    at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:299)
    at org.jboss.weld.introspector.jlr.WeldMethodImpl.invoke(WeldMethodImpl.java:193)
    at org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:591)
    … 76 more
    Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-4021] (Eclipse Persistence Services – 2.1.0.v20100614-r7608): org.eclipse.persistence.exceptions.DatabaseException
    Exception Description: Unable to acquire a connection from driver [null], user [null] and URL [null]. Verify that you have set the expected driver class and URL. Check your login, persistence.xml or sessions.xml resource. The jdbc.driver property should be set to a class that is compatible with your database platform
    at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:408)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getServerSession(EntityManagerFactoryImpl.java:157)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:214)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:202)
    at br.gov.frameworkdemoiselle.internal.producer.EntityManagerProducer.create(EntityManagerProducer.java:114)
    at br.gov.frameworkdemoiselle.internal.producer.EntityManagerProducer.init(EntityManagerProducer.java:180)
    … 86 more
    Caused by: Exception [EclipseLink-4021] (Eclipse Persistence Services – 2.1.0.v20100614-r7608): org.eclipse.persistence.exceptions.DatabaseException
    Exception Description: Unable to acquire a connection from driver [null], user [null] and URL [null]. Verify that you have set the expected driver class and URL. Check your login, persistence.xml or sessions.xml resource. The jdbc.driver property should be set to a class that is compatible with your database platform
    at org.eclipse.persistence.exceptions.DatabaseException.unableToAcquireConnectionFromDriverException(DatabaseException.java:376)
    at org.eclipse.persistence.sessions.DefaultConnector.connect(DefaultConnector.java:91)
    at org.eclipse.persistence.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:162)
    at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:579)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:228)
    at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:380)
    … 91 more

    at org.jboss.weld.bootstrap.events.AbstractDeploymentContainerEvent.fire(AbstractDeploymentContainerEvent.java:55)
    at org.jboss.weld.bootstrap.events.AfterDeploymentValidationImpl.fire(AfterDeploymentValidationImpl.java:34)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:393)
    at org.jboss.weld.environment.se.Weld.initialize(Weld.java:88)
    at org.jboss.weld.environment.se.StartMain.go(StartMain.java:45)
    at org.jboss.weld.environment.se.StartMain.main(StartMain.java:57)
    at br.gov.frameworkdemoiselle.util.DemoiselleRunner.init(DemoiselleRunner.java:56)
    at br.gov.frameworkdemoiselle.util.DemoiselleRunner.(DemoiselleRunner.java:50)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.(JUnit4TestReference.java:32)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.(JUnit4TestClassReference.java:25)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:41)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:31)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    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)

  2. 2 Rudolfo Borges

    Problema resolvido, usei o persistence configurada para tomcat e seu certo. Vlw

  3. 3 programmer

    poderia postar seu persistence estou com o mesmo problema


E aí, o que você achou? Comenta aí...

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s