2017-02-20 6 views
0

Некоторые, возможно, полезную информацию:Не удается запустить Arquillian с вложенным Glassfish

  • проекта: Maven на основе КДИ
  • среда: Ubuntu 16,04
  • JDK: оракул 8
  • IDE: Netbeans 8,2

Вот что испытывает CDI Bean:

@Named 
@SessionScoped 
public class UserPreferencies implements Serializable { 

private Locale currentLocale; 

public UserPreferencies() { 
    //locale is initiated to French but may be overriden in the 
    //post-constructed method 
    currentLocale = new Locale("fr"); 
} 

@PostConstruct 
public void initialize() { 
    /** 
    * if a user specific locale is provided in the browser 
    * we should be setting it here 
    */ 
    if(FacesContext.getCurrentInstance() != null){ 
     Optional<ExternalContext> optContext = ofNullable(FacesContext.getCurrentInstance() 
       .getExternalContext()); 
     if (optContext.isPresent()) { 
      Optional<Locale> userLocale = ofNullable(optContext.get().getRequestLocale()); 
      if (userLocale.isPresent()) { 
       currentLocale = userLocale.get(); 
      } 
     } 
    } 
} 

public Locale getCurrentLocale() { 
    return currentLocale; 
} 

public void setCurrentLocale(Locale currentLocale) { 
    this.currentLocale = currentLocale; 
} 

} 

Эти соответствующие параметры pom.xml (пишется после official arquillian guide):

<dependencies> 
    ... 
    <!-- the support for the arquillian test framework --> 
    <dependency> 
     <groupId>org.jboss.arquillian</groupId> 
     <artifactId>arquillian-bom</artifactId> 
     <version>1.1.11.Final</version> 
     <scope>import</scope> 
     <type>pom</type> 
    </dependency> 
    <dependency> 
     <groupId>org.jboss.arquillian.junit</groupId> 
     <artifactId>arquillian-junit-container</artifactId> 
     <version>1.1.11.Final</version> 
     <scope>test</scope> 
    </dependency> 
</dependencies> 
<profiles> 
    <profile> 
     <id>arquillian-glassfish-embedded</id> 
     <dependencies> 
      <dependency> 
       <groupId>org.jboss.arquillian.container</groupId> 
       <artifactId>arquillian-glassfish-embedded-3.1</artifactId> 
       <version>1.0.0.CR4</version> 
       <scope>test</scope> 
       <exclusions> 
         <exclusion> <groupId>org.jboss.arquillian.container</groupId> 
          <artifactId>arquillian-container-spi</artifactId> 
         </exclusion> 
        </exclusions> 
      </dependency> 
      <dependency> 
       <groupId>org.glassfish.main.extras</groupId> 
       <artifactId>glassfish-embedded-all</artifactId> 
       <version>3.1.2</version> 
       <scope>provided</scope> 
      </dependency> 
     </dependencies> 
    </profile> 
</profiles> 

Тогда я набор указанных выше профилей Maven с помощью опции Netbeans' 'Установка стандартной конфигурации'.

Это испытание, которое я пытаюсь запустить (довольно простой, как вы можете видеть):

@RunWith(Arquillian.class) 
public class UserPreferenciesTests { 

public UserPreferenciesTests() { 
} 

//humble attempt to mock glassfish only with the UserPreferencies bean inside 
@Deployment 
public static JavaArchive createDeployment() { 
    JavaArchive jar = ShrinkWrap.create(JavaArchive.class) 
      .addClass(UserPreferencies.class) 
      .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); 
    System.out.println(jar.toString(true)); 
    return jar; 
} 

@Inject 
UserPreferencies preferencies; 

@Test 
public void localeIsNotNull(){ 
    assertNotNull(preferencies.getCurrentLocale().getCountry()); 
} 

@Test 
public void defaultLocaleTest() { 
    assertTrue("The default locale should be \"fr\"", 
      "fr".equalsIgnoreCase(preferencies.getCurrentLocale().getLanguage())); 
} 
} 

Unfortunatelly выполнения теста, получаем следующее StackTrace:

Running com.vgorcinschi.rimmanew.cdi.UserPreferenciesTests 
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.512 sec <<< FAILURE! - in com.vgorcinschi.rimmanew.cdi.UserPreferenciesTests 
com.vgorcinschi.rimmanew.cdi.UserPreferenciesTests Time elapsed: 0.51 sec <<< ERROR! 
java.lang.RuntimeException: Could not create new instance of class org.jboss.arquillian.test.impl.EventTestRunnerAdaptor 
    at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:165) 
    at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:102) 
    at org.jboss.arquillian.test.spi.TestRunnerAdaptorBuilder.build(TestRunnerAdaptorBuilder.java:52) 
    at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:113) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128) 
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203) 
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155) 
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103) 
Caused by: java.lang.reflect.InvocationTargetException: null 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 
    at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:161) 
    at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:102) 
    at org.jboss.arquillian.test.spi.TestRunnerAdaptorBuilder.build(TestRunnerAdaptorBuilder.java:52) 
    at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:113) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128) 
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203) 
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155) 
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103) 
Caused by: java.lang.NoSuchMethodError: org.jboss.shrinkwrap.descriptor.api.DescriptorImporter.fromString(Ljava/lang/String;)Lorg/jboss/shrinkwrap/descriptor/api/Descriptor; 
    at org.jboss.arquillian.config.impl.extension.ConfigurationSysPropResolver.resolveSystemProperties(ConfigurationSysPropResolver.java:55) 
    at org.jboss.arquillian.config.impl.extension.ConfigurationRegistrar.loadConfiguration(ConfigurationRegistrar.java:71) 
    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:498) 
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94) 
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99) 
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81) 
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145) 
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116) 
    at org.jboss.arquillian.core.impl.ManagerImpl.start(ManagerImpl.java:290) 
    at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.<init>(EventTestRunnerAdaptor.java:63) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 
    at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:161) 
    at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:102) 
    at org.jboss.arquillian.test.spi.TestRunnerAdaptorBuilder.build(TestRunnerAdaptorBuilder.java:52) 
    at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:113) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153) 
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128) 
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203) 
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155) 
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103) 


Results : 

Tests in error: 
    UserPreferenciesTests.com.vgorcinschi.rimmanew.cdi.UserPreferenciesTests » Runtime 

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

------------------------------------------------------------------------ 
BUILD FAILURE 

Любые советы или совместно эксперт по этому вопросу ценится, поскольку, хотя я много читал на аркильском сайте, я довольно новичок в тестировании с Аркиллиан на практической стороне.

[Update] Выполнение mvn dependency:tree -Dverbose я понял один конфликт зависимостей для новых библиотек, которые вызвали более новая библиотека будет пропущено (я обновил файл POM выше). Это новая ошибка (org.jvnet.hk2.component.MultiMap действительно отсутствует в проекте, но библиотека, которую я исключил не был удален - это как заменить на правильную версию ...):

com.vgorcinschi.rimmanew.cdi.UserPreferenciesTests Time elapsed: 
0.666 sec <<< ERROR! 
java.lang.NoSuchMethodError: org.jvnet.hk2.component.MultiMap.<init>(Z)V 
    at org.jvnet.hk2.component.Habitat.<init>(Habitat.java:127) 
    at org.jvnet.hk2.component.Habitat.<init>(Habitat.java:120) 
    at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.newHabitat(AbstractModulesRegistryImpl.java:118) 
    at com.sun.enterprise.module.bootstrap.Main.createHabitat(Main.java:444) 
    at com.sun.enterprise.glassfish.bootstrap.StaticGlassFishRuntime.newGlassFish(StaticGlassFishRuntime.java:104) 
    at org.jboss.arquillian.container.glassfish.embedded_3_1.GlassFishContainer.setup(GlassFishContainer.java:147) 
    at org.jboss.arquillian.container.glassfish.embedded_3_1.GlassFishContainer.setup(GlassFishContainer.java:67) 
    at org.jboss.arquillian.container.impl.ContainerImpl.setup(ContainerImpl.java:181) 
    at org.jboss.arquillian.container.impl.client.container.ContainerLifecycleController$7.perform(ContainerLifecycleController.java:149) 
    at org.jboss.arquillian.container.impl.client.container.ContainerLifecycleController$7.perform(ContainerLifecycleController.java:145) 
    at org.jboss.arquillian.container.impl.client.container.ContainerLifecycleController.forContainer(ContainerLifecycleController.java:255) 
    at org.jboss.arquillian.container.impl.client.container.ContainerLifecycleController.setupContainer(ContainerLifecycleController.java:144) 
    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:498) 
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94) 
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99) 
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81) 

...

+0

Разве вам не нужно добавлять shrinkwrap явно как зависимость? '<Зависимости> org.jboss.shrinkwrap.resolver Shrinkwrap-распознаватель-depchain тест П ' –

+0

Я пытаюсь добавить его (обратите внимание, что версия пропускает ваш фрагмент) - дает тот же результат. – vasigorc

ответ

1

Наконец-то я понял это. Я отправляю его на случай, если это может быть полезно для других людей, испытывающих подобные проблемы. Все проблемы возникали из противоречивых зависимостей, но многие из них были невидимы, потому что я использовал glassfish-embedded-all (и позже payara-embedded-all в качестве замены) с предоставленной областью. Один за другим я начал удалять зависимости, которые бросали эти ошибки. Например, старая зависимость hk2 исходила от org.glassfish.jersey.core:jersey-client:2.21.

Тогда у меня была аналогичная проблема с org.apache.deltaspike.core:deltaspike-core-impl:1.01. При этом возникла еще одна проблема - именно она использовалась каркасом cdi-unit в одном тестовом методе. Полагая, что блок cdi и arquillian делают то же самое, но более поздняя версия намного более мощная, я закончил, исключив этот метод тестирования.

Это пом.xml, который работал для меня (я исключил ненужные части), но если у вас есть аналогичная проблема, попробуйте следовать той же логике, исключая старые зависимости и «чистую установку» каждый раз, чтобы проверить, что ничего не сломается :-):

<?xml version="1.0" encoding="UTF-8"?> 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 

... 

<properties> 
    <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> 
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
    <spring.version>4.3.1.RELEASE</spring.version> 
</properties> 

<dependencies> 
    ... 
    <dependency> 
     <groupId>javax</groupId> 
     <artifactId>javaee-web-api</artifactId> 
     <version>7.0</version> 
     <scope>provided</scope> 
    </dependency> 
    <dependency> 
     <groupId>org.glassfish.jersey.core</groupId> 
     <artifactId>jersey-client</artifactId> 
     <version>2.21</version> 
     <!-- important hk2 were excluded because they shadowed the provided 
     arquillian dependencies with higher version. Should the hk2 library be needed 
     add this artifact: org.glassfish.hk2:hk2:2.5.0-b32  --> 
     <exclusions> 
      <exclusion> 
       <groupId>org.glassfish.hk2</groupId> 
       <artifactId>hk2-api</artifactId> 
      </exclusion> 
      <exclusion> 
       <groupId>org.glassfish.hk2</groupId> 
       <artifactId>hk2-locator</artifactId> 
      </exclusion> 
     </exclusions> 
    </dependency> 
    <dependency> 
     <groupId>org.glassfish.jersey.media</groupId> 
     <artifactId>jersey-media-json-jackson</artifactId> 
     <version>2.21</version> 
     <scope>provided</scope> 
    </dependency> 
    <dependency> 
     <groupId>org.glassfish</groupId> 
     <artifactId>javax.json</artifactId> 
     <version>1.0.4</version> 
     <scope>test</scope> 
    </dependency> 
    ... 
    <dependency> 
     <groupId>junit</groupId> 
     <artifactId>junit</artifactId> 
     <version>4.12</version> 
     <scope>test</scope> 
    </dependency> 
    <dependency> 
     <groupId>org.hamcrest</groupId> 
     <artifactId>hamcrest-library</artifactId> 
     <version>1.3</version> 
     <scope>test</scope> 
     <type>jar</type> 
    </dependency>  
    <dependency> 
     <groupId>org.easymock</groupId> 
     <artifactId>easymock</artifactId> 
     <version>3.3.1</version> 
     <scope>test</scope> 
    </dependency> 
    <dependency> 
     <groupId>org.jglue.cdi-unit</groupId> 
     <artifactId>cdi-unit</artifactId> 
     <version>3.1.3</version> 
     <exclusions>     
      <exclusion> 
       <groupId>org.jboss.weld.se</groupId> 
       <artifactId>weld-se-core</artifactId> 
      </exclusion> 
      <exclusion> 
       <groupId>org.easymock</groupId> 
       <artifactId>easymock</artifactId> 
      </exclusion> 
      <exclusion> 
       <groupId>org.testng</groupId> 
       <artifactId>testng</artifactId> 
      </exclusion> 
      <exclusion> 
       <groupId>javax.servlet</groupId> 
       <artifactId>javax.servlet-api</artifactId> 
      </exclusion> 
      <exclusion> 
       <groupId>org.mockito</groupId> 
       <artifactId>mockito-all</artifactId> 
      </exclusion> 
      <exclusion> 
       <groupId>com.sun.faces</groupId> 
       <artifactId>jsf-api</artifactId> 
      </exclusion> 
      <exclusion> 
       <groupId>org.apache.deltaspike.core</groupId> 
       <artifactId>deltaspike-core-impl</artifactId> 
      </exclusion> 
     </exclusions> 
     <scope>test</scope>       
    </dependency>   
    <dependency> 
     <groupId>org.jboss.weld.se</groupId> 
     <artifactId>weld-se-core</artifactId> 
     <version>2.2.2.Final</version> 
     <scope>test</scope> 
     <exclusions> 
      <exclusion> 
       <groupId>com.google.guava</groupId> 
       <artifactId>guava</artifactId> 
      </exclusion> 
     </exclusions> 
    </dependency> 
    <dependency> 
     <groupId>mysql</groupId> 
     <artifactId>mysql-connector-java</artifactId> 
     <version>5.1.35</version> 
     <scope>test</scope> 
     <type>jar</type> 
    </dependency> 
    <!-- the support for the arquillian test framework -->   
    <dependency> 
     <groupId>org.jboss.arquillian.junit</groupId> 
     <artifactId>arquillian-junit-container</artifactId> 
     <scope>test</scope> 
    </dependency> 
    <dependency> 
     <groupId>org.jboss.arquillian.container</groupId> 
     <artifactId>arquillian-glassfish-embedded-3.1</artifactId> 
     <version>1.0.0.CR4</version> 
     <scope>test</scope> 
    </dependency> 
    <dependency> 
     <groupId>fish.payara.extras</groupId> 
     <artifactId>payara-embedded-all</artifactId> 
     <version>4.1.1.161</version> 
     <scope>test</scope> 
    </dependency>  
</dependencies> 
<dependencyManagement> 
    <dependencies> 
     <dependency> 
      <groupId>org.jboss.arquillian</groupId> 
      <artifactId>arquillian-bom</artifactId> 
      <version>1.1.11.Final</version> 
      <scope>import</scope> 
      <type>pom</type> 
     </dependency>  
    </dependencies> 
</dependencyManagement>  
<build> 
    <plugins> 
     <plugin> 
      <groupId>org.apache.maven.plugins</groupId> 
      <artifactId>maven-surefire-plugin</artifactId> 
      <version>2.18.1</version> 
     </plugin> 
     <plugin> 
      <groupId>org.apache.maven.plugins</groupId> 
      <artifactId>maven-compiler-plugin</artifactId> 
      <version>3.3</version> 
      <configuration> 
       <source>1.8</source> 
       <target>1.8</target> 
       <compilerArguments> 
        <endorseddirs>${endorsed.dir}</endorseddirs> 
       </compilerArguments> 
      </configuration> 
     </plugin> 
     <plugin> 
      <groupId>org.apache.maven.plugins</groupId> 
      <artifactId>maven-war-plugin</artifactId> 
      <version>2.3</version> 
      <configuration> 
       <failOnMissingWebXml>false</failOnMissingWebXml> 
      </configuration> 
     </plugin> 
     <plugin> 
      <groupId>org.apache.maven.plugins</groupId> 
      <artifactId>maven-dependency-plugin</artifactId> 
      <version>2.9</version> 
      <executions> 
       <execution> 
        <phase>validate</phase> 
        <goals> 
         <goal>copy</goal> 
        </goals> 
        <configuration> 
         <outputDirectory>${endorsed.dir}</outputDirectory> 
         <silent>true</silent> 
         <artifactItems> 
          <artifactItem> 
           <groupId>javax</groupId> 
           <artifactId>javaee-endorsed-api</artifactId> 
           <version>7.0</version> 
           <type>jar</type> 
          </artifactItem> 
         </artifactItems> 
        </configuration> 
       </execution> 
      </executions> 
     </plugin> 
    </plugins> 
</build> 
... 

Заметим также, что я обновил Java-файлы (в этом вопросе), чтобы улучшить логическую часть тестов.

Смежные вопросы