couldn't resolve error: java.lang.NoSuchFieldError: FAIL_ON_SYMBOL_HASH_OVERFLOW- elasticsearch java client api - elasticsearch

I'm trying to implement an autocomplete feature using elaticsearch 6.2.4 and its java rest client API on my maven web application which is running under glassfish 4.1
I am facing the below error:
java.lang.NoSuchFieldError: FAIL_ON_SYMBOL_HASH_OVERFLOW
I have read some about it and made changes accordingly essentially on project dependencies( inside pom.xml) because all responses that I met, turned around conflict on Jackson library version.
here is the code that I tried to run:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")
));
SearchRequest searchRequest = new SearchRequest( "trustiser_suggest" );
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
String[] includeFields = new String[] {"member_mname","member_pic","member_fname","member_lname","topic_label"};
String[] excludeFields = null;
searchSourceBuilder.fetchSource(includeFields, excludeFields);
Map<String, List<? extends ToXContent>> contextMap = new HashMap<>();
contextMap.put("account_state", Collections.singletonList(CategoryQueryContext.builder().setCategory("active").build()));
SuggestionBuilder termSuggestionBuilder = SuggestBuilders.completionSuggestion("suggest_member" )
.prefix( str )
.contexts(contextMap);
SuggestBuilder suggestBuilder = new SuggestBuilder();
suggestBuilder.addSuggestion( "suggest-mem", termSuggestionBuilder );
SuggestionBuilder termSuggestionBuilder1 = SuggestBuilders.completionSuggestion("suggest_topic" )
.prefix( str )
.skipDuplicates(true);
suggestBuilder.addSuggestion( "suggest-top", termSuggestionBuilder1 );
searchSourceBuilder.suggest( suggestBuilder);
searchRequest.source( searchSourceBuilder );
SearchResponse searchResponse = null;
searchResponse = client.search( searchRequest );
System.out.println("AutoCompleteMemberTopicccccccccccccccc: "+searchResponse.toString());
my curent pom.xml:
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>6.2.4</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
and the error:
java.lang.NoSuchFieldError: FAIL_ON_SYMBOL_HASH_OVERFLOW
at org.elasticsearch.common.xcontent.json.JsonXContent.<clinit>(JsonXContent.java:57)
at org.elasticsearch.common.xcontent.XContentFactory.contentBuilder(XContentFactory.java:121)
at org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder.contexts(CompletionSuggestionBuilder.java:203)
at com.trustiser.business.ElasticSearchDao1.AutoCompleteMemberTopic(ElasticSearchDao1.java:50)
at com.trustiser.service.SearchEngineService.searchMemberCategory(SearchEngineService.java:33)
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.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103)
and finally the maven tree of the web project
--- maven-dependency-plugin:2.8:tree (default-cli) # elasticmavenprojet ---
com.trustiser:elasticmavenprojet:war:1.0-SNAPSHOT
+- javax:javaee-web-api:jar:7.0:provided
+- com.fasterxml.jackson.core:jackson-core:jar:2.8.10:compile
+- org.elasticsearch:elasticsearch:jar:6.2.4:compile
| +- org.elasticsearch:elasticsearch-core:jar:6.2.4:compile
| +- org.apache.lucene:lucene-core:jar:7.2.1:compile
| +- org.apache.lucene:lucene-analyzers-common:jar:7.2.1:compile
| +- org.apache.lucene:lucene-backward-codecs:jar:7.2.1:compile
| +- org.apache.lucene:lucene-grouping:jar:7.2.1:compile
| +- org.apache.lucene:lucene-highlighter:jar:7.2.1:compile
| +- org.apache.lucene:lucene-join:jar:7.2.1:compile
| +- org.apache.lucene:lucene-memory:jar:7.2.1:compile
| +- org.apache.lucene:lucene-misc:jar:7.2.1:compile
| +- org.apache.lucene:lucene-queries:jar:7.2.1:compile
| +- org.apache.lucene:lucene-queryparser:jar:7.2.1:compile
| +- org.apache.lucene:lucene-sandbox:jar:7.2.1:compile
| +- org.apache.lucene:lucene-spatial:jar:7.2.1:compile
| +- org.apache.lucene:lucene-spatial-extras:jar:7.2.1:compile
| +- org.apache.lucene:lucene-spatial3d:jar:7.2.1:compile
| +- org.apache.lucene:lucene-suggest:jar:7.2.1:compile
| +- org.elasticsearch:securesm:jar:1.2:compile
| +- org.elasticsearch:elasticsearch-cli:jar:6.2.4:compile
| | \- net.sf.jopt-simple:jopt-simple:jar:5.0.2:compile
| +- com.carrotsearch:hppc:jar:0.7.1:compile
| +- joda-time:joda-time:jar:2.9.9:compile
| +- org.yaml:snakeyaml:jar:1.17:compile
| +- com.fasterxml.jackson.dataformat:jackson-dataformat-smile:jar:2.8.10:compile
| +- com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:jar:2.8.10:compile
| +- com.fasterxml.jackson.dataformat:jackson-dataformat-cbor:jar:2.8.10:compile
| +- com.tdunning:t-digest:jar:3.0:compile
| +- org.hdrhistogram:HdrHistogram:jar:2.1.9:compile
| +- org.apache.logging.log4j:log4j-api:jar:2.9.1:compile
| \- org.elasticsearch:jna:jar:4.5.1:compile
+- org.elasticsearch.client:elasticsearch-rest-client:jar:6.2.4:compile
| +- org.apache.httpcomponents:httpclient:jar:4.5.2:compile
| +- org.apache.httpcomponents:httpcore:jar:4.4.5:compile
| +- org.apache.httpcomponents:httpasyncclient:jar:4.1.2:compile
| +- org.apache.httpcomponents:httpcore-nio:jar:4.4.5:compile
| +- commons-codec:commons-codec:jar:1.10:compile
| \- commons-logging:commons-logging:jar:1.1.3:compile
+- org.elasticsearch.client:elasticsearch-rest-high-level-client:jar:6.2.4:compile
| +- org.elasticsearch.plugin:parent-join-client:jar:6.2.4:compile
| | +- org.locationtech.spatial4j:spatial4j:jar:0.6:compile
| | +- com.vividsolutions:jts:jar:1.13:compile
| | \- org.apache.logging.log4j:log4j-core:jar:2.9.1:compile
| +- org.elasticsearch.plugin:aggs-matrix-stats-client:jar:6.2.4:compile
| \- org.elasticsearch.plugin:rank-eval-client:jar:6.2.4:compile
\- com.googlecode.json-simple:json-simple:jar:1.1.1:compile
\- junit:junit:jar:4.10:compile
\- org.hamcrest:hamcrest-core:jar:1.1:compile
Thank you :-)

You are right, this is an error message thrown by the Jackson library which elasticsearch uses for JSON serialization and deserialization And caused by having a conflicting version of Jackson library.
I can see you are explicitly including a Jackson library by defining below dependency in your pom.xml.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.10</version>
</dependency>
And by looking at your mvn tree, I see elasticsearch is also bringing some Jackson libraries. Can you try below 2 options?
Option 1. Remove the explicit Jackson dependency which I just mentioned, and do a clean build. (Note this is less likely to work :), but there is no harm to try.
option 2. I looked at my project and I am using the elasticsearch 7.1 and using the below Jackson core library.
com.fasterxml.jackson.core:jackson-core:jar:2.9.8:compile
If you can't figure out which is the compatible jackson core version for your es version, then you can just upgrade to elasticsearch 7.1 and use the Jackson version I provided and it should work.

after several days of work and research, I finally find the solution of my problem.
The problem is caused by a version conflict between dependencies of ES hight level client api and those existing on glassfish modules ( Jackson-core is one of them).
Because replacing jars of glassfish module directory is a risky practice, the solution that I applied is to shade the ES dependency and rename there packages using maven shade plugin.
These are followed steps to implement the solution:
Create the shaded dependency of ES:
Create a java maven project;
The Pom.xml of the project:
<modelVersion>4.0.0</modelVersion>
<groupId>com.trustiser</groupId>
<artifactId>elasticshade</artifactId>
<version>6.2.4</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.2.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<relocation>
<pattern>org.elasticsearch</pattern>
<shadedPattern>hidden.org.elasticsearch</shadedPattern>
</relocation>
<relocation>
<pattern>org.apache.lucene</pattern>
<shadedPattern>hidden.org.apache.lucene</shadedPattern>
</relocation>
<relocation>
<pattern>com.fasterxml</pattern>
<shadedPattern>hidden.com.fasterxml</shadedPattern>
</relocation>
<relocation>
<pattern>org.apache.httpcomponents</pattern>
<shadedPattern>hidden.org.apache.httpcomponents</shadedPattern>
</relocation>
<relocation>
<pattern>org.hdrhistogram</pattern>
<shadedPattern>hidden.org.hdrhistogram</shadedPattern>
</relocation>
<relocation>
<pattern>org.slf4j</pattern>
<shadedPattern>hidden.org.slf4j</shadedPattern>
</relocation>
<relocation>
<pattern>org.yaml</pattern>
<shadedPattern>hidden.org.yaml</shadedPattern>
</relocation>
<relocation>
<pattern>net.sf.jopt-simple</pattern>
<shadedPattern>hidden.net.sf.jopt-simple</shadedPattern>
</relocation>
<relocation>
<pattern>joda-time</pattern>
<shadedPattern>hidden.joda-time</shadedPattern>
</relocation>
<relocation>
<pattern>commons-logging</pattern>
<shadedPattern>hidden.commons-logging</shadedPattern>
</relocation>
<relocation>
<pattern>commons-codec</pattern>
<shadedPattern>hidden.commons-codec</shadedPattern>
</relocation>
<relocation>
<pattern>com.tdunning</pattern>
<shadedPattern>hidden.com.tdunning</shadedPattern>
</relocation>
<relocation>
<pattern>com.github.spullara</pattern>
<shadedPattern>hidden.com.github.spullara</shadedPattern>
</relocation>
<relocation>
<pattern>com.carrotsearch</pattern>
<shadedPattern>hidden.com.carrotsearch</shadedPattern>
</relocation>
</relocations>
<shadedArtifactAttached>false</shadedArtifactAttached>
<artifactSet>
<includes>
<include>*:*</include>
</includes>
</artifactSet>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.PluginXmlResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.trustiser.elasticshade.App</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Run clean, build and maven package goal;
The jar will be created on "elastic shade project location" \target
Add the shaded dependency on maven local repository:
Access to m2 repository from the cmd, the default location is C:\Users\"user".m2\repository , and execute the following command to istall the created dependency: mvn install:install-file -Dfile="location of the shaded elastic dependency".jar -DgroupId="shaded dependency groupe id" -DartifactId="shaded dependency acrifact id" -Dversion="version of the shaded dependency" -Dpackaging=jar
Add the shaded dependency of elasticsearch on the pom.xml of my maven java web application instead of using elasticsearch hight level rest api directly
To avoid log4j error I add a log4j2.properties file on the resources directory of my java web app :
appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%d{ISO8601}][%-5p][%-25c] %marker%m%n
rootLogger.level = info
rootLogger.appenderRef.console.ref = console

Related

Maven does not see testng tests when testing Spring Boot Application is running

I setup simple Spring Boot project to serve basic HTML pages. I wrote a kind of integration tests with testNG. Now, I want to run my tests with maven does not see my tests.
STR:
Run mvn spring-boot:run
Run mvn test
Output:
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------------< vznd:selenium >----------------------------
[INFO] Building selenium 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) # selenium ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 0 resource
[INFO] Copying 27 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) # selenium ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:testResources (default-testResources) # selenium ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] skip non existing resourceDirectory C:\Users\vladyslav.kovalenko\OneDrive - FORM.com\Documents\den\selenium-webdriver-tests\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) # selenium ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:3.0.0-M6:test (default-test) # selenium ---
[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.963 s
[INFO] Finished at: 2022-05-09T13:03:51+01:00
[INFO] ------------------------------------------------------------------------
pom.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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>vznd</groupId>
<artifactId>selenium</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<maven-surefire-plugin.version>3.0.0-M6</maven-surefire-plugin.version>
<testng.version>7.5</testng.version>
<selenium-java.version>3.141.59</selenium-java.version>
<commons-io.version>2.11.0</commons-io.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium-java.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<systemPropertyVariables>
<webdriver.chrome.driver>/tmp/chromedriver/chromedriver</webdriver.chrome.driver>
</systemPropertyVariables>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</project>
testng.xml:
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name="SeleniumApp Tests" parallel="false">
<test name="Selenium Test">
<classes>
<class name="vznd.selenium.AlertsControllerTest"/>
<class name="vznd.selenium.GettingBrowserInformationTest"/>
<class name="vznd.selenium.FramesTest"/>
<class name="vznd.selenium.BrowserNavigationTest"/>
<class name="vznd.selenium.KeyboardActionsTest"/>
<class name="vznd.selenium.WindowsTest"/>
</classes>
</test>
</suite>
Test example:
package vznd.selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class FramesTest extends BaseTest {
#BeforeMethod
public void openPageWithIframes() {
driver.get(HTMLPath.FRAMES);
}
#Test
public void switchToFrameUsingWebElement() {
WebElement greenFrame = driver.findElement(By.id("first-iframe"));
driver.switchTo().frame(greenFrame);
WebElement table = driver.findElement(By.cssSelector("table[id='green-table']"));
Assert.assertNotNull(table, "The table WebElement object was null!");
}
}
Spring Boot Application:
package vznd.selenium;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SeleniumApp {
public static void main(String[] args) {
SpringApplication.run(SeleniumApp.class, args);
}
}
Controller example:
package vznd.selenium.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class FramesController {
#GetMapping("/iframes")
public String iframes() {
return "iframes";
}
}
I tried to google about similar problems, but most answers is about naming test classes with *Test suffix and that is not my case.
The tests are executed in IDEA by right-click on the project -> Run -> All tests.
Please, advice me how I can get tests executed with maven.
If you see the logs surefire is not detecting TestNG.
Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider
If you remove SpringBoot will be: Using auto detected provider org.apache.maven.surefire.testng.TestNGProvider
Try adding TestNG dependency to surefire plugin:
<project>
...
<dependencies>
...
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-testng</artifactId>
<version>3.0.0-M5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<systemPropertyVariables>
<webdriver.chrome.driver>/tmp/chromedriver/chromedriver</webdriver.chrome.driver>
</systemPropertyVariables>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-testng</artifactId>
<version>3.0.0-M5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>

mvn test command not running tests in a Spring Boot project

This is my pom file
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.ricardo</groupId>
<artifactId>cdh</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cdh</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<azure.version>2.2.0</azure.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.1.44</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-core</artifactId>
<version>1.1.44</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.6</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-storage</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-security-keyvault-secrets</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-eventhubs</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-spring-boot-bom</artifactId>
<version>${azure.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>local</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<activatedProperties>local</activatedProperties>
</properties>
</profile>
<profile>
<id>dev</id>
<properties>
<activatedProperties>dev</activatedProperties>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<activatedProperties>test</activatedProperties>
</properties>
</profile>
</profiles>
</project>
When I run mvn test this is the output and none of the test run. However every test work as expected using the IDE Intellij.
[INFO] Building cdh 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) # cdh ---
[INFO] Deleting /Users/ricardochampa/mypath/target
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) # cdh ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 4 resources
[INFO] Copying 4 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) # cdh ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 140 source files to /Users/mypath/cdh-back/target/classes
[INFO] /Users/mypath/cdh-back/src/main/java/com/ricardo/cdh/mappers/OrdersMapper.java: Some input files use unchecked or unsafe operations.
[INFO] /Users/mypath/cdh-back/src/main/java/com/ricardo/cdh/mappers/OrdersMapper.java: Recompile with -Xlint:unchecked for details.
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) # cdh ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/mypath/cdh-back/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) # cdh ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 6 source files to /Users/mypath/cdh-back/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) # cdh ---
[INFO]
[INFO] -------------------------< com.ricardo:cdh >--------------------------
[INFO] Building cdh 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) # cdh ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 4 resources
[INFO] Copying 4 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) # cdh ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) # cdh ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/mypath/cdh-back/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) # cdh ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) # cdh ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.484 s
[INFO] Finished at: 2020-09-30T22:18:05+02:00
[INFO] ------------------------------------------------------------------------
UPDATE
I've just try with the following pom.xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<includes>
<include>*Test.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
And I tried this as well.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<includes>
<include>customWildcardPattern</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
And this...
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
And this...
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
</plugins>
</build>
None of them works :(
The project structure.
An example of test class: ProductsServiceTest
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
public class ProductsServiceTest {
#Mock ProductsRepository productsRepository;
#Mock ResourceService resourceService;
#Autowired #InjectMocks ProductsService service;
private ProductsEntity productsEntity = new ProductsEntity();
private final String stubSearchText = "search this text with results";
private final String stubSearchTextNoResults = "search this text without results";
private final String notFoundStubID = "ID NOT EXISTS";
private final String stubID = "id";
private final String stubName = "name";
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
productsEntity.setId(stubID);
productsEntity.setName(stubName);
when(productsRepository.findById(stubID)).thenReturn(Optional.of(productsEntity));
when(productsRepository.findById(notFoundStubID)).thenReturn(Optional.empty());
doNothing().when(resourceService).changeResourceStatus(any(String.class), any(String.class));
List<ProductsEntity> productsEntityList = new ArrayList<>();
productsEntityList.add(productsEntity);
when(productsRepository.searchProducts(stubSearchText)).thenReturn(productsEntityList);
}
#Test
public void whenGetProduct() throws CdhException {
ProductsDto productsDto = service.getProduct(stubID);
assertEquals(productsDto.getId(), stubID);
assertEquals(productsDto.getName(), stubName);
}
#Test
public void whenGetProductNotExist() {
assertThatThrownBy(() -> service.getProduct(notFoundStubID)).isInstanceOf(CdhException.class);
}
#Test
public void whenCreateProduct() {
ProductsDto dto = new ProductsDto();
dto.setId("fake id");
dto.setIdResource("fake id resource");
service.createProduct(dto);
verify(service.productsRepository).save(any(ProductsEntity.class));
}
#Test
public void whenDeleteProduct() throws CdhException {
service.deleteProduct(stubID);
verify(service.productsRepository).save(any(ProductsEntity.class));
}
}
I finally fix it.
My problems was JUnit4, according to docs https://maven.apache.org/surefire/maven-surefire-plugin/examples/junit.html I should add the plugin like this.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit4</artifactId>
<version>3.0.0-M5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
1. First potential root cause : Test class naming
Make sure that your test class name matchs one of those default Maven Surefire plugin patterns:
Test*.java
*Test.java
*Tests.java
*TestCase.java
If you need to customize it, you need to add :
<project>
[...]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<includes>
<include>TO_BE_REPLACED_BY_YOUR_CUSTOM_WILDCARD_PATTERN</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
[...]
</project>
###UPDATE####:
2. Second potential root cause that may lead to not executing test is the exclusion part in your spring-boot-starter-test
Replace:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
by:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
maven surefire plugin is missing in your pom.xml.
Be sure to annotate your test methods with #Test:
import org.junit.jupiter.api.Test; // <-- or whatever you are using..
public class SomeTest {
...
#Test // <----
public void testSomething() {
...
}
...
}
The key here is to understand the test engines that Spring uses.
In my case, I coded API tests with #RunWith(SpringRunner.class), which is under JUnit4, which runs with junit-vintage-engine.
But the unit tests are coded with JUnit Jupiter, which is under JUnit5, which runs with junit-jupiter-engine.
The default engine of SpringBoot is the junit-jupiter-engine. So we have to tell to Spring that we also want to use junit-vintage-engine.
We can simply add the dependency in our pom.xml:
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
Or, if we want to use maven-surefire, we can add the dependency inside the plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<dependencies>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.7.0</version>
</dependency>
</dependencies>
</plugin>

Jacoco + JUnit 5.0 DynamicTest not working

I am trying to generate a code coverage report using Jacoco with JUnit 5 and Spring Boot. And I"m trying to use the DynamicTest feature of JUnit 5. It runs successfully but the Dynamic Tests are not covered in the test coverage report generated by jacoco. Is JUnit 5 Dynamic Test not covered by Jacoco at the moment?
Here is the code:
#RunWith(JUnitPlatform.class)
#SelectPackages("com.troll.jpt.abc.model")
#SelectClasses({Status.class})
public class DynamicModelTester {
private Status status;
#BeforeEach
public void setUp() {
status = new Status();
}
#TestFactory
public Stream<DynamicTest> checkDynamicTestsFromStream() {
List<String> input = Arrays.asList("abc");
List<String> output = Arrays.asList("abc");
status.setCode(input.get(0));
return input.stream().map(str -> DynamicTest.dynamicTest("status test", () -> {
assertEquals(output.get(0), status.getCode());
}));
}
}
The jacoco plugin I'm using is as :
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.2-SNAPSHOT</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<!-- Sets the path to the file which contains the execution data. -->
<dataFile>target/jacoco.exec</dataFile>
<!-- Sets the output directory for the code coverage report. -->
<outputDirectory>target/jacoco-ut</outputDirectory>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile>
</systemPropertyVariables>
</configuration>
</plugin>
It runs successfully but the Dynamic Tests are not covered in the test coverage report generated by jacoco.
jacoco-maven-plugin:report doesn't display coverage in tests, it displays coverage of a target of a test - in your case target seems to be class Status, whose definition is completely absent. For future I highly recommend to read https://stackoverflow.com/help/mcve and follow its recommendations, especially part about "Complete":
Make sure all information necessary to reproduce the problem is included
Generic answer on questions like "does JaCoCo support JUnit 5 Dynamic Test?" is: JaCoCo records fact that code was executed independently from the way how it was executed - via JUnit 4 or JUnit 5, or even manually or whatever the other way of execution.
And generic answer on questions like "why some code is not marked as covered?" is: make sure that code is actually executed, in case of automatic tests this means - make sure that these tests are actually executed.
But let's give a try with JUnit 5 Dynamic Test. In absence of src/main/java/Status.java I'll assume that it is something like
public class Status {
private String code;
public void setCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
No idea why you need systemPropertyVariables, snapshot version of jacoco-maven-plugin, multiple executions of report and redundant specification of dataFile with its default value, so will also assume that complete pom.xml after slight cleanup looks like
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>example</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>1.2.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.21.0</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.1</version>
<configuration>
<outputDirectory>target/jacoco-ut</outputDirectory>
</configuration>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
After placing
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
#RunWith(JUnitPlatform.class)
#SelectPackages("com.troll.jpt.abc.model")
#SelectClasses({Status.class})
public class DynamicModelTester {
private Status status;
#BeforeEach
public void setUp() {
status = new Status();
}
#TestFactory
public Stream<DynamicTest> dynamicTestsFromStream() {
List<String> input = Arrays.asList("abc");
List<String> output = Arrays.asList("abc");
status.setCode(input.get(0));
return input.stream().map(str -> DynamicTest.dynamicTest("status test", () -> {
assertEquals(output.get(0), status.getCode());
}));
}
}
into src/test/java/DynamicModelTester.java and execution of mvn clean verify:
[INFO] --- maven-surefire-plugin:2.21.0:test (default-test) # example ---
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) # example ---
[INFO] Building jar: /private/tmp/jacoco/target/example-1.0-SNAPSHOT.jar
[INFO]
[INFO] --- jacoco-maven-plugin:0.8.1:report (default) # example ---
[INFO] Skipping JaCoCo execution due to missing execution data file.
Last line is quite suspicious as well as absence of number of tests executed by maven-surefire-plugin together with absence of target/surefire-reports/.
Let's rename DynamicModelTester into DynamicModelTest and execute mvn clean verify again:
[INFO] --- maven-surefire-plugin:2.21.0:test (default-test) # example ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running DynamicModelTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.023 s - in DynamicModelTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) # example ---
[INFO] Building jar: /private/tmp/jacoco/target/example-1.0-SNAPSHOT.jar
[INFO]
[INFO] --- jacoco-maven-plugin:0.8.1:report (default) # example ---
[INFO] Loading execution data file /private/tmp/jacoco/target/jacoco.exec
[INFO] Analyzed bundle 'example' with 1 classes
Compared to previous attempt test was executed this time. And coverage report target/jacoco-ut/default/Status.html looks like:
I believe that the reason of the fact that test is not executed lies in a default value of includes of maven-surefire-plugin :
A list of elements specifying the tests (by pattern) that
should be included in testing. When not specified and when the test
parameter is not specified, the default includes will be
<includes>
<include>**/Test*.java</include>
<include>**/*Test.java</include>
<include>**/*Tests.java</include>
<include>**/*TestCase.java</include>
</includes>
DynamicModelTester.java doesn't match any of these patters, while DynamicModelTest.java matches second, but I'll leave verification of this as a little exercise.

Missing jacoco.exec file when using jacoco offline instrumentation with Powermock

Despite apparently this post showed a solution to using powermock and jacoco, I haven't been able to make it work in a pretty simple project (available on GitHub).
In my case, the test executes correctly but the jacoco.exec file is missing so jacoco doesn't check coverage.
Test class:
#RunWith(PowerMockRunner.class)
#PrepareOnlyThisForTest(Util.class)
#PowerMockIgnore("org.jacoco.agent.rt.*")
public class UtilTest {
#Test
public void testSay() throws Exception {
PowerMockito.mockStatic(Util.class);
Mockito.when(Util.say(Mockito.anyString())).thenReturn("hello:mandy");
Assert.assertEquals("hello:mandy", Util.say("sid"));
}
}
Util.java
public class Util {
private Util() {}
public static String say(String s) {
return "hello:"+s;
}
}
pom.xml
<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>
<groupId>com.codependent.jacocopower</groupId>
<artifactId>jacoco-powermock</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<systemPropertyVariables>
<jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<id>default-instrument</id>
<goals>
<goal>instrument</goal>
</goals>
</execution>
<execution>
<id>default-restore-instrumented-classes</id>
<goals>
<goal>restore-instrumented-classes</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule>
<element>CLASS</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0.50</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>org.jacoco.agent</artifactId>
<classifier>runtime</classifier>
<version>${jacoco.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<powermock.version>1.5.4</powermock.version>
<jacoco.version>0.7.4.201502262128</jacoco.version>
</properties>
</project>
Maven execution trace, complaining that no jacoco.exec file was found:
>> mvn clean verify
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building jacoco-powermock 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) # jacoco-powermock ---
[INFO] Deleting C:\SoftDesarrollo\6-Workspaces\libertyGecon\jacoco-powermock\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) # jacoco-powermock ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) # jacoco-powermock ---
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\SoftDesarrollo\6-Workspaces\libertyGecon\jacoco-powermock\target\classes
[INFO]
[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:instrument (default-instrument) # jacoco-powermock ---
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) # jacoco-powermock ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:testCompile (default-testCompile) # jacoco-powermock ---
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 1 source file to C:\SoftDesarrollo\6-Workspaces\libertyGecon\jacoco-powermock\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) # jacoco-powermock ---
[INFO] Surefire report directory: C:\SoftDesarrollo\6-Workspaces\libertyGecon\jacoco-powermock\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.codependent.jacoco.UtilTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.239 sec - in com.codependent.jacoco.UtilTest
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:restore-instrumented-classes (default-restore-instrumented-classes) # jacoco-powermock ---
[INFO]
[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (default-report) # jacoco-powermock ---
[INFO] Skipping JaCoCo execution due to missing execution data file:C:\SoftDesarrollo\6-Workspaces\libertyGecon\jacoco-powermock\target\jacoco.exec
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) # jacoco-powermock ---
[INFO] Building jar: C:\SoftDesarrollo\6-Workspaces\libertyGecon\jacoco-powermock\target\jacoco-powermock-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:check (default-check) # jacoco-powermock ---
[INFO] Skipping JaCoCo execution due to missing execution data file:C:\SoftDesarrollo\6-Workspaces\libertyGecon\jacoco-powermock\target\jacoco.exec
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.987s
[INFO] Finished at: Thu Jan 21 09:13:55 CET 2016
[INFO] Final Memory: 23M/331M
[INFO] ------------------------------------------------------------------------
UPDATE: (here on GitHub)
With the answer provided by Lencalot the jacoco.exec file is generated but the following scenario keeps saying that the ServiceImpl class coverage is 0%:
ServiceImpl
public class ServiceImpl implements Service{
public String operation() {
return Util.say("Hi!");
}
}
ServiceTest
#RunWith(PowerMockRunner.class)
#PrepareForTest({Util.class})
public class ServiceTest {
private Service service = new ServiceImpl();
#Test
public void testOperation() throws Exception {
PowerMockito.mockStatic(Util.class);
Mockito.when(Util.say(Mockito.anyString())).thenReturn("Bye!");
Assert.assertEquals("Bye!", service.operation());
}
}
Trace:
[WARNING] Rule violated for class com.codependent.jacoco.ServiceImpl: lines covered ratio is 0.00, but expected minimum is 0.50
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<configuration>
<append>true</append>
</configuration>
<executions>
<execution>
<id>default-instrument</id>
<goals>
<goal>instrument</goal>
</goals>
<configuration>
<includes>
<include>**/*test*</include>
</includes>
</configuration>
</execution>
<execution>
<id>default-restore-instrumented-classes</id>
<goals>
<goal>restore-instrumented-classes</goal>
</goals>
<configuration>
<includes>
<include>**/*test*</include>
</includes>
</configuration>
</execution>
<execution>
<id>Prepare-Jacoco</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*test*</exclude>
</excludes>
</configuration>
</execution>
</executions>
</plugin>
you can remove Check for now, we can try to get it working with out that first.
Update your Jacoco dependency to look like this
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>org.jacoco.agent</artifactId>
<version>${jacoco.version}</version>
<scope>test</scope>
</dependency>
Make you maven surefire plugin look like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>${argLine}</argLine>
</configuration>
</plugin>
in your properties section Add this as, and change your jacoco Version:
<jacoco.version>0.7.5.201505241946</jacoco.version>
<jacoco.outputDir>${project.basedir}/target/jacoco.exec</jacoco.outputDir>
#codependent Heres an example of why you want to mock.
Lets assume your Util.class has a lot more code, a lot of instantiations and maybe it even touches some server side stuff, hell maybe even its a UI. You don't want to instantiate User.class just to test a single method in some other class called UtilUser.class
protected class UtilUser {
protected UtilUser() {}
public Boolean checkSay(String s) {
String expectedString = "hello:" + s;
String actualString = Util.say(s);
if (expectedString.equals(actualString){
return true;
} else {
return false;
}
}
}
To unit test UtilUser, you want to hit all branches. So in your test you would mock the Util.class, and in one unit test force it to return the correct string, and in another test have it return an incorrect string. You don't care about testing User.class, you know it will behave accordingly or you will have another test to take care of that. For unit testing UtilUser, you can expect Util to either return a correct string or an incorrect string, and you want to test both possibilities.
Theres a time and a place for mocks and they are a great tool to know, but DO NOT think they should be used often. Please refer to the following article, it will give you good insight into when you should use mocks: When To Mock

Cannot run Arquillian test case on Glassfish

I am stuck very badly in a very simple implementation of an Arquillian test case. I followed Can I add jars to maven 2 build classpath without installing them? to add my project jars to maven repository. I am using Glassfish server as my application server.
Then I need to write arquillian test cases.
For that I used the following code
#Inject
private ControllerLoginModule controllerloginmodule;
#Deployment
public static WebArchive createDeployment()
{
File[] lib = Maven.resolver()
.resolve("com.controllerjars:controllerbeans:1.0.0","com.controllerjars:controllerapi:2.0.0","com.controllerjars:controllerauth:1.0.0")
.withTransitivity().as(File.class);
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(ControllerLoginModule.class,AuthRealm.class,IAccountManagerInternal.class)
.addAsLibraries(lib)
.addAsWebInfResource(new StringAsset("<beans/>"), "beans.xml")
.addAsWebInfResource(new StringAsset("<web-app></web-app>"), "web.xml");
}
#Test
public void testIsDeployed()
{
Assert.assertNotNull(controllerloginmodule);
}
Basically I am loading some jars which contains Classes Under Test and the classes on which those classes depends. In the end I am trying to create a web archive out of it.
Then I try to test that wether object is null or not.
The issue which I can figure out from the stack trace is the deployment is not able to find the files from Maven. Below is the stack trace observed when I try to run the test case.
java.lang.RuntimeException: Could not invoke deployment method: public static org.jboss.shrinkwrap.api.spec.WebArchive com.appdynamics.auth.ControllerLoginModuleTest.createDeployment()
at org.jboss.arquillian.container.test.impl.client.deployment.AnnotationDeploymentScenarioGenerator.invoke(AnnotationDeploymentScenarioGenerator.java:160)
at org.jboss.arquillian.container.test.impl.client.deployment.AnnotationDeploymentScenarioGenerator.generateDeployment(AnnotationDeploymentScenarioGenerator.java:94)
at org.jboss.arquillian.container.test.impl.client.deployment.AnnotationDeploymentScenarioGenerator.generate(AnnotationDeploymentScenarioGenerator.java:57)
at org.jboss.arquillian.container.test.impl.client.deployment.DeploymentGenerator.generateDeployment(DeploymentGenerator.java:79)
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.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:135)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:115)
at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67)
at org.jboss.arquillian.container.test.impl.client.ContainerEventController.execute(ContainerEventController.java:100)
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.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.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:75)
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.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:60)
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.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:135)
at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:115)
at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.beforeClass(EventTestRunnerAdaptor.java:80)
at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:182)
at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:314)
at org.jboss.arquillian.junit.Arquillian.access$100(Arquillian.java:46)
at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:199)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:147)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
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.arquillian.container.test.impl.client.deployment.AnnotationDeploymentScenarioGenerator.invoke(AnnotationDeploymentScenarioGenerator.java:156)
... 50 more
Caused by: java.lang.RuntimeException: Could not create new descriptor instance
at org.jboss.shrinkwrap.resolver.api.DependencyBuilderInstantiator.createFromUserView(DependencyBuilderInstantiator.java:101)
at org.jboss.shrinkwrap.resolver.api.DependencyResolvers.use(DependencyResolvers.java:39)
at com.appdynamics.auth.ControllerLoginModuleTest.createDeployment(ControllerLoginModuleTest.java:51)
... 55 more
Caused by: java.lang.reflect.InvocationTargetException
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.jboss.shrinkwrap.resolver.api.DependencyBuilderInstantiator.createFromUserView(DependencyBuilderInstantiator.java:96)
... 57 more
Caused by: java.lang.NoSuchMethodError: org.codehaus.plexus.DefaultPlexusContainer.lookup(Ljava/lang/Class;)Ljava/lang/Object;
at org.jboss.shrinkwrap.resolver.impl.maven.MavenRepositorySystem.getRepositorySystem(MavenRepositorySystem.java:220)
at org.jboss.shrinkwrap.resolver.impl.maven.MavenRepositorySystem.<init>(MavenRepositorySystem.java:64)
at org.jboss.shrinkwrap.resolver.impl.maven.MavenBuilderImpl.<init>(MavenBuilderImpl.java:105)
... 62 more
I can't understand where and what I am missing. I have updated the entries for dependencies given in the Can I add jars to maven 2 build classpath without installing them?. Any help is greatly appreciated.
Thanks.
Below is my pom
<?xml version="1.0" encoding="UTF-8"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- Model Information -->
<modelVersion>4.0.0</modelVersion>
<!-- Artifact Information -->
<groupId>com.auth</groupId>
<artifactId>controller.functionaltest</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<!-- Properties -->
<properties>
<version.shrinkwrap.resolver>2.0.0-beta-2</version.shrinkwrap.resolver>
<version.junit>4.11</version.junit>
<version.arquillian_core>1.0.3.Final</version.arquillian_core>
<project.basedir>/controller.functionaltest</project.basedir>
<version.org.jboss.shrinkwrap>1.1.2</version.org.jboss.shrinkwrap>
</properties>
<!-- Dependency Management -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-bom</artifactId>
<version>${version.shrinkwrap.resolver}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>${version.arquillian_core}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!-- Dependencies -->
<dependencies>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>1.0.0.Final</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${version.junit}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<version>${version.arquillian_core}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.controllerjars</groupId>
<artifactId>commonscollections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.controllerjars</groupId>
<artifactId>commonutil</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.controllerjars</groupId>
<artifactId>controllerapi</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.controllerjars</groupId>
<artifactId>controllerauth</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.controllerjars</groupId>
<artifactId>controllerbeans</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-depchain</artifactId>
<type>pom</type>
<version>2.0.0-beta-2</version>
</dependency>
</dependencies>
<!-- Repositories -->
<repositories>
<repository>
<id>JBOSS_NEXUS</id>
<url>http://repository.jboss.org/nexus/content/groups/public</url>
</repository>
<repository>
<releases>
<enabled>true</enabled>
<checksumPolicy>ignore</checksumPolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>repo</id>
<url>file://${project.basedir}/src/main/resources</url>
</repository>
</repositories>
<!-- Plugin Configuration -->
<build>
<finalName>controller.functionaltest</finalName>
<!-- Compiler -->
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
<!-- Plugin Management -->
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.apache.maven.plugins
</groupId>
<artifactId>
maven-dependency-plugin
</artifactId>
<versionRange>[2.1,)</versionRange>
<goals>
<goal>unpack</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
<profile>
<id>GLASSFISH_REMOTE_3.1_(REST)</id>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<extensions>false</extensions>
<executions>
<execution>
<id>unpack</id>
<phase>process-test-classes</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.jboss.as</groupId>
<artifactId>jboss-as-dist</artifactId>
<version>7.1.3.Final</version>
<type>zip</type>
<overWrite>false</overWrite>
<outputDirectory>~/JBOSS_Managed</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-remote-3.1</artifactId>
<version>1.0.0.CR3</version>
</dependency>
</dependencies>
</profile>
<profile>
<id>JBOSS_AS_MANAGED_7.X</id>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<extensions>false</extensions>
<executions>
<execution>
<id>unpack</id>
<phase>process-test-classes</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.jboss.as</groupId>
<artifactId>jboss-as-dist</artifactId>
<version>7.1.3.Final</version>
<type>zip</type>
<overWrite>false</overWrite>
<outputDirectory>~/JBOSS_Managed</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.jboss.as</groupId>
<artifactId>jboss-as-arquillian-container-managed</artifactId>
<version>7.1.3.Final</version>
</dependency>
</dependencies>
</profile>
</profiles>
</project>
below is my Dependency tree .
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building controller.functionaltest 1.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.1:tree (default-cli) # controller.functionaltest ---
[INFO] com.appdynamics.auth:controller.functionaltest:pom:1.0.0-SNAPSHOT
[INFO] +- org.jboss.spec:jboss-javaee-6.0:pom:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.annotation:jboss-annotations-api_1.1_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.resource:jboss-connector-api_1.5_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.ejb:jboss-ejb-api_3.1_spec:jar:1.0.0.Final:provided
[INFO] | | \- javax.xml:jaxrpc-api:jar:1.1:provided
[INFO] | +- org.jboss.spec.javax.el:jboss-el-api_2.2_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.interceptor:jboss-interceptors-api_1.1_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.security.jacc:jboss-jacc-api_1.4_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.enterprise.deploy:jboss-jad-api_1.2_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.security.auth.message:jboss-jaspi-api_1.0_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.xml.registry:jboss-jaxr-api_1.0_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.jms:jboss-jms-api_1.1_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.servlet.jsp:jboss-jsp-api_2.2_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.transaction:jboss-transaction-api_1.1_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.xml.bind:jboss-jaxb-api_2.2_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.xml.rpc:jboss-jaxrpc-api_1.1_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.xml.soap:jboss-saaj-api_1.3_spec:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.spec.javax.xml.ws:jboss-jaxws-api_2.2_spec:jar:1.0.0.Final:provided
[INFO] | +- javax.activation:activation:jar:1.1:provided
[INFO] | +- javax.enterprise:cdi-api:jar:1.0-SP4:provided
[INFO] | +- com.sun.faces:jsf-api:jar:2.0.3-b05:provided
[INFO] | +- javax.inject:javax.inject:jar:1:provided
[INFO] | +- javax.jws:jsr181-api:jar:1.0-MR1:provided
[INFO] | +- javax.mail:mail:jar:1.4.2:provided
[INFO] | +- javax.servlet:jstl:jar:1.2:provided
[INFO] | +- org.hibernate.javax.persistence:hibernate-jpa-2.0-api:jar:1.0.0.Final:provided
[INFO] | +- org.jboss.resteasy:jaxrs-api:jar:2.1.0.GA:provided
[INFO] | +- stax:stax-api:jar:1.0.1:provided
[INFO] | \- javax.validation:validation-api:jar:1.0.0.GA:provided
[INFO] +- junit:junit:jar:4.11:test (scope not updated to runtime)
[INFO] | \- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] +- org.jboss.arquillian.junit:arquillian-junit-container:jar:1.0.3.Final:test
[INFO] | +- org.jboss.arquillian.junit:arquillian-junit-core:jar:1.0.3.Final:test
[INFO] | +- org.jboss.arquillian.test:arquillian-test-api:jar:1.0.3.Final:test
[INFO] | | \- org.jboss.arquillian.core:arquillian-core-api:jar:1.0.3.Final:test
[INFO] | +- org.jboss.arquillian.test:arquillian-test-spi:jar:1.0.3.Final:test
[INFO] | | \- org.jboss.arquillian.core:arquillian-core-spi:jar:1.0.3.Final:test
[INFO] | +- org.jboss.arquillian.container:arquillian-container-test-api:jar:1.0.3.Final:test
[INFO] | +- org.jboss.arquillian.container:arquillian-container-test-spi:jar:1.0.3.Final:test
[INFO] | | \- org.jboss.arquillian.container:arquillian-container-spi:jar:1.0.3.Final:test
[INFO] | | \- org.jboss.shrinkwrap.descriptors:shrinkwrap-descriptors-api-base:jar:2.0.0-alpha-3:test
[INFO] | +- org.jboss.arquillian.core:arquillian-core-impl-base:jar:1.0.3.Final:test
[INFO] | +- org.jboss.arquillian.test:arquillian-test-impl-base:jar:1.0.3.Final:test
[INFO] | +- org.jboss.arquillian.container:arquillian-container-impl-base:jar:1.0.3.Final:test
[INFO] | | +- org.jboss.arquillian.config:arquillian-config-api:jar:1.0.3.Final:test
[INFO] | | +- org.jboss.arquillian.config:arquillian-config-impl-base:jar:1.0.3.Final:test
[INFO] | | \- org.jboss.shrinkwrap.descriptors:shrinkwrap-descriptors-spi:jar:2.0.0-alpha-3:test
[INFO] | \- org.jboss.arquillian.container:arquillian-container-test-impl-base:jar:1.0.3.Final:test
[INFO] +- com.controllerjars:commonscollections:jar:3.2.1:compile
[INFO] +- com.controllerjars:commonutil:jar:1.0.0:compile
[INFO] +- com.controllerjars:controllerapi:jar:2.0.0:compile
[INFO] +- com.controllerjars:controllerauth:jar:1.0.0:compile
[INFO] +- com.controllerjars:controllerbeans:jar:1.0.0:compile
[INFO] \- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-depchain:pom:2.0.0-beta-2:compile
[INFO] +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-api:jar:2.0.0-beta-2:compile
[INFO] +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-spi:jar:2.0.0-beta-2:compile
[INFO] +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-api-maven:jar:2.0.0-beta-2:compile
[INFO] +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-impl-maven:jar:2.0.0-beta-2:runtime
[INFO] | +- org.sonatype.aether:aether-api:jar:1.13.1:runtime
[INFO] | +- org.sonatype.aether:aether-impl:jar:1.13.1:runtime
[INFO] | +- org.sonatype.aether:aether-spi:jar:1.13.1:runtime
[INFO] | +- org.sonatype.aether:aether-util:jar:1.13.1:runtime
[INFO] | +- org.sonatype.aether:aether-connector-wagon:jar:1.13.1:runtime
[INFO] | +- org.apache.maven:maven-aether-provider:jar:3.0.4:runtime
[INFO] | +- org.apache.maven:maven-model:jar:3.0.4:runtime
[INFO] | +- org.apache.maven:maven-model-builder:jar:3.0.4:runtime
[INFO] | +- org.apache.maven:maven-repository-metadata:jar:3.0.4:runtime
[INFO] | +- org.apache.maven:maven-settings:jar:3.0.4:runtime
[INFO] | +- org.apache.maven:maven-settings-builder:jar:3.0.4:runtime
[INFO] | +- org.codehaus.plexus:plexus-interpolation:jar:1.14:runtime
[INFO] | +- org.codehaus.plexus:plexus-utils:jar:2.0.6:runtime
[INFO] | +- org.apache.maven.wagon:wagon-provider-api:jar:2.2:runtime
[INFO] | +- org.apache.maven.wagon:wagon-file:jar:2.2:runtime
[INFO] | \- org.apache.maven.wagon:wagon-http-lightweight:jar:2.2:runtime
[INFO] | \- org.apache.maven.wagon:wagon-http-shared4:jar:2.2:runtime
[INFO] | +- org.jsoup:jsoup:jar:1.6.1:runtime
[INFO] | +- org.apache.httpcomponents:httpcore:jar:4.1.2:runtime
[INFO] | \- commons-io:commons-io:jar:2.0.1:runtime
[INFO] \- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-impl-maven-archive:jar:2.0.0-beta-2:runtime
[INFO] +- org.jboss.shrinkwrap:shrinkwrap-impl-base:jar:1.0.1:runtime
[INFO] | +- org.jboss.shrinkwrap:shrinkwrap-api:jar:1.0.1:runtime
[INFO] | \- org.jboss.shrinkwrap:shrinkwrap-spi:jar:1.0.1:runtime
[INFO] +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-api-maven-archive:jar:2.0.0-beta-2:runtime
[INFO] +- org.jboss.shrinkwrap.resolver:shrinkwrap-resolver-spi-maven-archive:jar:2.0.0-beta-2:runtime
[INFO] +- org.codehaus.plexus:plexus-compiler-javac:jar:2.1:runtime
[INFO] | \- org.codehaus.plexus:plexus-compiler-api:jar:2.1:runtime
[INFO] \- org.codehaus.plexus:plexus-component-api:jar:1.0-alpha-33:runtime
[INFO] \- org.codehaus.plexus:plexus-classworlds:jar:1.2-alpha-10:runtime
I think the cause of this problem is due to ambiguous ShrinkWrap Resolver dependencies. You should declare the ShrinkWrap Resolver Bill of Materials in the dependency Management chain before the Arquillian BOM. I recommend using the ShrinkWrap Resolver 2.0.0-beta-2.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-bom</artifactId>
<version>2.0.0-beta-2</version>
<scope>test</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>${arquillian.version}</version>
<scope>test</scope>
<type>pom</type>
</dependency>
</dependencyManagement>
In the dependency section you need to have the following dependencies present:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-depchain</artifactId>
<type>pom</type>
<version>2.0.0-beta-2</version>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<version>${arquillian.version}</version>
<scope>test</scope>
</dependency>
The ShrinkWrap Resolver 2.0.0-beta-2 provides a new API for resolving artifacts, so you need to make sure you use that particular API, such as:
File lib = Maven.resolver()
.resolve("artifact-groupid:artifact-artifactid:version")
.withoutTransitivity()
.asSingle(File.class);
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClass(MyClass.class)
.addAsLibrary(lib)
.addAsWebInfResource(new StringAsset("<beans/>"), "beans.xml")
.addAsWebInfResource(new StringAsset("<web-app></web-app>"), "web.xml");
I've created an example project containing the bare minimums needed to make use of ShrinkWrap Resolver which makes use of the configuration and code above, however running in an embedded TomEE container. You can find it here: https://github.com/tommysdk/showcase/tree/master/arquillian-shrinkres. Hopefully this can help you to straight out the correct dependencies and versions needed.
I had the same issue. The reason was that a resource file could not be reached. Example:
.addAsWebResource("index.html")
Index.html file must be in classpath during the test runtime or else the exception that throws is (!):
java.lang.RuntimeException: Could not invoke deployment method: public static org.jboss.shrinkwrap.api.Archive com.intrasoft.ssp.persistence.admin.service.IndexPageTest.createDeployment()
Your POM looks like it is lending to a conflict or missing dependency among the ShrinkWrap artifacts pulled in by Arquillian BOM and the ShrinkWrap Resolvers depchain.
Going by the POM snippet here, I believe you should also add the ShrinkWrap Resolver BOM as a managed dependency, before the Arquillian BOM, in your project POM.

Resources