Тесты с Wildfly 8 и NetBeans
Вопрос
У меня возникли проблемы, делая тестирование подвижков под NetBeans и Maven.Я могу запустить приложение из IDE, я даже могу отладить его с отладчиком NetBeans, однако, как только я начнут тесты на единицу, я получаю следующую ошибку:
No EJBContainer provider available: no provider names had been found.
javax.ejb.EJBException
at javax.ejb.embeddable.EJBContainer.reportError(EJBContainer.java:216)
at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:146)
at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:102)
at cz.interactsys.ejb.StatefulSessionBeanTest.setUp(StatefulSessionBeanTest.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
.
Код является стандартным, как следующее:
int numberA = 1;
int numberB = 2;
EJBContainer container = javax.ejb.embeddable.EJBContainer.createEJBContainer();
MyBean instance = (MyBean) container.getContext().lookup("java:global/classes/MyBean");
int expResult = 3;
int result = instance.plusOne(1);
assertEquals(expResult, result);
container.close();
.
Спасибо заранее.
Решение
Проблема в том, что нет EJBContainer в Wildfly вообще. Я не уверен, что это возможно, учитывая, что EJBContainer должен быть там в соответствии с спецификацией платформы. Тем не менее нам нужно использовать что-то другое, и это аркил. Этот текст был вдохновлен многочисленными другими статьями, Maily этот один , однако, решение, предложенное здесь, использует одну и ту же установку для пробоев для тестов, что и для регулярного развертывания, которое кажется мне лучше. < / P >.
Тщательно внимательно следовать следующим советам. Тогда это будет работать.
шаг нулю - подготовка: Давайте подготовимся что-то, что мы можем использовать для тестирования.
Давайте устроим регулярный проект Maven Javaee, то есть.:
demoproj
demoproj-ear
demoproj-ejb
demoproj-war
.
Я использую NetBeans, однако следующие шаги не должны быть очень разными даже для других идентификаторов. Давайте создадим некоторые вещи, такие как бобы сущности, настойчивости и сессионные бобы, конечно, чтобы иметь что-то, чтобы проверить. Я создал демонстрацию демонстрации демонстрации, используя NetBeans, сущность, используя базу данных и сессионный боб от объекта.
<Сильный> Шаг первый: Добавляем следующий код в pom.xml od demoproj (то есть главный проект):
<properties>
<junit-version>4.11</junit-version>
<arquillian-version>1.1.4.Final</arquillian-version>
<arquillian-wildfly-version>8.1.0.Final</arquillian-wildfly-version>
<arquillian-transaction-version>1.0.1.Final</arquillian-transaction-version>
<javaee-server-home>/Java/wildfly-8.1.0.Final</javaee-server-home>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee-api-version}</version>
</dependency>
<!-- -JUNIT-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
</dependency>
<!-- rquillian itself-->
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>${arquillian-version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
<!-- this is in an extention to arquillian it is optional-->
<dependency>
<groupId>org.jboss.arquillian.extension</groupId>
<artifactId>arquillian-transaction-bom</artifactId>
<version>${arquillian-transaction-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- this is container adapter for wildfly-->
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-embedded</artifactId>
<version>${arquillian-wildfly-version}</version>
</dependency>
<!-- this is the wildfly emb.container - BUT eventually it is not a fully blown emb.container-->
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-embedded</artifactId>
<version>${arquillian-wildfly-version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<!-- compiler plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin-version}</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<!-- maven ear plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-ear-plugin</artifactId>
<version>${ear-plugin-version}</version>
<configuration>
<generateModuleId>true</generateModuleId>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
<!-- ejb plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-ejb-plugin</artifactId>
<version>${ejb-plugin-version}</version>
<configuration>
<ejbVersion>${ejb-spec-version}</ejbVersion>
</configuration>
</plugin>
<!-- war plugin -skinny wars mode! -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${war-plugin-version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
</archive>
<webResources>
<resource>
<filtering>true</filtering>
<directory>src/main/webapp</directory>
<includes>
<include>**/web.xml</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
</plugin>
</plugins>
</pluginManagement>
</build>
.
Шаг 2: Мы добавляем следующее в раздел зависимости Pom.xml demoproj-ejb:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-embedded</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-embedded</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.extension</groupId>
<artifactId>arquillian-transaction-jta</artifactId>
<scope>test</scope>
</dependency>
.
Добавьте это в раздел плагинов DEMOPROJ-EJB:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Dfile.encoding=UTF-8</argLine>
<forkCount>1C</forkCount>
<systemPropertyVariables>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
<jboss.home>${javaee-server-home}</jboss.home>
</systemPropertyVariables>
<redirectTestOutputToFile>false</redirectTestOutputToFile>
</configuration>
</plugin>
.
Шаг третий: Давайте создадим тестовый блок. Если мы используем нормальную функцию IDE, мы получаем что-то вроде следующего:
package com.demopack.demoproj;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class DemoBeanLocalTest {
public DemoBeanLocalTest() {
}
@Before
public void setUp() {
}
@Test
public void testBusinessMethod() {
}
}
.
Теперь нам нужно добавить @RunWith(Arquillian.class)
непосредственно перед заголовком класса, вы должны удалить конструктор по умолчанию и добавить следующий код в классе тестирования:
@EJB
DemoBeanLocal demoBean;
@Deployment
public static JavaArchive createDeployment() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class);
jar.addAsResource("test-persistence.xml", "META-INF/persistence.xml");
jar.addPackage("com.demopack.demoproj");
jar.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
return jar;
}
.
Тогда вы можете добавить некоторые методы тестирования как обычно. Весь тестовый класс может выглядеть следующее:
package com.demopack.demoproj;
import javax.ejb.EJB;
import junit.framework.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class DemoBeanLocalTest {
@EJB
DemoBeanLocal demoBean;
@Deployment
public static JavaArchive createDeployment() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class);
jar.addAsResource("test-persistence.xml", "META-INF/persistence.xml");
jar.addPackage("com.demopack.demoproj");
jar.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
return jar;
}
@Before
public void setUp() {
}
@Test
public void testBusinessMethod() {
Assert.assertEquals("test test", demoBean.businessMethod("test"));
}
}
.
src/test/resources
и скопируйте там persistence.xml
от src/main/resources/META-INF
и переименовать его на GeneracodicTacode.
Убедитесь, что запущена база данных, установлен действительный драйвер, используется правильный источник данных и т. Д. В моем случае большинство неприятностей были вызваны проблемами такого рода.
test-persistence.xml
, и если все будет хорошо, вы можете использовать обычные функции тестирования NetBeans, как вы используете. Наслаждайтесь!
в Pom.xml в главном проекте:
Обмен:
`<artifactId>wildfly-arquillian-container-embedded</artifactId>` for
`<artifactId>wildfly-arquillian-container-remote</artifactId>`.
.
Удалить:
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-embedded</artifactId>
<version>${arquillian-wildfly-version}</version>
</dependency>
.
Тогда сделайте то же самое в pom.xml demoproj-ejb.