I am unable to control the treads from dataproviderthreadcount.
For example if we have 4 scenario and I run my script, it execute all 4 scenario's parallelly. Doesn't matter what dataproviderthreadcount value I gave in the pom for maven-surfire.
Below are the snapshots.
POM:
<?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>
<groupId>org.example</groupId>
<artifactId>testParallerRun</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<cucumbertestng.version>5.6.0</cucumbertestng.version>
<cucumberjava.version>5.6.0</cucumberjava.version>
<mvncompiler.version>3.8.1</mvncompiler.version>
<javarelease.version>11</javarelease.version>
<mvnsurefire.version>3.0.0-M5</mvnsurefire.version>
</properties>
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>${cucumbertestng.version}</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumberjava.version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${mvncompiler.version}</version>
<configuration>
<release>${javarelease.version}</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${mvnsurefire.version}</version>
<configuration>
<properties>
<property>
<name>dataproviderthreadcount</name>
<value>2</value>
</property>
</properties>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Runner Class:
package com.test.runner;
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
import org.testng.annotations.DataProvider;
#CucumberOptions(
plugin = {
"pretty",
"json:target/reports/json/result.json",
"html:target/reports/html/result.html"},
strict = true,
features = {"src/test/resources/"},
glue = {"com.test.stepdef"},
tags = {""}
)
public class TestRunner extends AbstractTestNGCucumberTests {
#DataProvider(parallel = true)
#Override
public Object[][] scenarios() {
return super.scenarios();
}
}
Feature 1:
Feature: test 1
Scenario: 01
Given Print "01"
Scenario: 02
Given Print "02"
Scenario: 03
Given Print "03"
Scenario: 04
Given Print "04"
Please let me if anyone know how to control the number of threads rather than let Testng decide.
There's no problem with TestNG per se here.
The dataproviderthreadcount attribute that you have set in your pom file is going to be applicable and relevant only when you are running your test via mvn clean test.
If you are trying to run this test class from within the IDE (IntelliJ or Eclipse for that matter) its not going take affect.
Here's a test class that I created which is powered by a data provider ( For the sake of simplicity I have intentionally kept cucumber out of the equation )
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class AppTest {
#Test(dataProvider = "dp")
public void shouldAnswerWithTrue(int i) {
System.err.println("Running on [" + Thread.currentThread().getId() + "]");
}
#DataProvider(name = "dp", parallel = true)
public Object[][] testData() {
return new Object[][]{
{1},
{2},
{3},
{4},
{5},
{6}
};
}
}
Here's the command line output when I run mvn clean test
[INFO] --- maven-surefire-plugin:3.0.0-M5:test (default-test) # testng_playground ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.rationaleemotions.AppTest
Running on [15]
Running on [14]
Running on [15]
Running on [14]
Running on [14]
Running on [15]
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.62 s - in com.rationaleemotions.AppTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
I encountered the exact same. As Krishnan mentioned, the dataproviderthreadcount in pom.xml works only when you run mvn test but without any parameter. If you want to specify which suite xml to run, you will need to add -Ddataproviderthreadcount=2 in command line as well. For example, "mvn -Dsurefire.suiteXmlFiles=suite.xml -Ddataproviderthreadcount=2 test"
Related
I am starting to use spring boot framework and stumble on every second step.
Currently I have a situation which i absolutely do not understand.
I am using spring boot 2.3.5.RELEASE building with maven
<properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.6.Final</version>
</dependency>
<!-- OpenAPi (swagger)-->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.2.32</version>
</dependency>
</dependencies>
I created a rather simple class RESTCommunication. No #Component, #Controller or similar.
public class RESTCommunication {
private final Logger m_logger = LoggerFactory.getLogger(this.getClass());
private String m_contentType;
private String m_path;
private String m_body;
private HashMap<String,String> m_urlParams;
private HashMap<String,String> m_queryParams;
public RESTCommunication() {
m_logger.debug("RESTCommunication constructor");
m_scheme = RESTCommunication.SCHEME_DEFAULT;
m_authority = RESTCommunication.AUTHORITY_DEFAULT;
m_port = RESTCommunication.PORT_DEFAULT;
m_path = RESTCommunication.PATH_DEFAULT;
m_urlParams = new HashMap<>();
// m_queryParams = new HashMap<>(); // I know that this is the reason for the exception
}
#Override
public String toString() {
StringBuilder sbToString = new StringBuilder();
sbToString.append(buildURI());
sbToString.append("|numURLParams:").append(m_urlParams.size());
sbToString.append("|numQueryParams:").append(m_queryParams.size()); // This has to fail because m_queryParams is not initialized
return sbToString.toString();
}
.....
For this class i created a very simple test class RESTCommunicationTest
#SpringBootTest
public class RESTCommunicationTest {
private final Logger m_logger = LoggerFactory.getLogger(this.getClass());
#Test
public void defaultInitTest() {
RESTCommunication restComm = new RESTCommunication();
String restCommURL = restComm.toString(); // Expect the nullpointer INSIDE the toString method
String expectedURL = sbExpected.toString();
assertEquals(expectedURL, restCommURL, "Expected URL does not match generated");
}
I run the test with the command: $./mvnw -e -X package -Dtest=RESTCommunicationTest#defaultInitTest
And as expectable i see the Nullpointer in the stdout logging.
BUT in the logging I find this:
webServerFactoryCustomizerBeanPostProcessor
websocketServletWebServerCustomizer
welcomePageHandlerMapping
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.532 s <<< FAILURE! - in org.highpots.hippo.core.communication.RESTCommunicationTest
[ERROR] defaultInitTest Time elapsed: 0.399 s <<< ERROR!
java.lang.NullPointerException
at org.ilovespringboot.not.RESTCommunicationTest.defaultInitTest(RESTCommunicationTest.java:36)
2020-12-08 22:18:10.810 INFO 10381 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] RESTCommunicationTest.defaultInitTest:36 » NullPointer
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
A nullpointer in RESTCommunicationTest.java:36. Absolutely no hint that the real NullPointer happens in RESTCommunication class.
Can someone explain my that behaviour? Am I doing something wrong?
I know I am some kind of programming dinosaurs. (java projects are about 10+ years in the past). But I would expect to get a hint where the exception is thrown. I would expect a stacktrace with detailed caused by sections.
If can not imagine this is not normal behavior. Because that would mean I have to find all errors by mind-stepping through the complete source... This is not possible
Tanks for your help in advance
Harri E
Maven uses surefire plugin to run tests.To see Exception stacktrace you must set trimStackTrace to false in surefire plugin configuration.
Historically surefire plugin use to print complete stacktrace. Though the information in the stack trace was useful for debugging, stack traces took up rather a lot of space in the console output. Particularly if there were a number of failing tests it became easy to get lost in the noise.
Since version 2.13 surefire just prints summary by default.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${your.maven.surefire.version.here}</version>
<configuration>
<trimStackTrace>false</trimStackTrace>
</configuration>
</plugin>
</plugins>
</build>
how to run all methods one by one in multiple class by setting priority using testng?
public class test1 {
#Test(priority = 1)
public void test1()
{
System.out.println("test1");
}
#Test(priority = 2)
public void test2()
{
System.out.println("test2");
}
}
public class test2 {
#Test(priority = 1)
public void test3()
{
System.out.println("test3");
}
#Test(priority = 2)
public void test4()
{
System.out.println("test4");
}
}
Expected output
test1
test2
test3
test4
but getting
test1
test3
test2
test4
how to run class 1 firs and then class 2?
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name="SANITY SUITE">
<test name="TESTCASE1" >
<classes>
<class name="demo.demo.test1"/>
<class name="demo.demo.test2"/>
</classes>
</test>
</suite>
In your suite xml use this: <test name="TESTCASE1" group-by-instances="true" >
https://stackoverflow.com/a/26635229/8794926
From the documentation (search for preserve-order)
By default, TestNG will run your tests in the order they are found in the XML file.
Assuming following structure
pom.xml
src/test/java/testng.xml
src/test/java/demo/demo/test2.java
src/test/java/demo/demo/test1.java
snippet in the pom.xml
<properties>
<maven.compiler.source>13</maven.compiler.source>
<maven.compiler.target>13</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.0.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${project.build.testSourceDirectory}/testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
testnng.xml - the one you provided
test1.java and test2.java - the ones you provided with added import and package statement
Running the tests as mvn test will produce the expected output
[INFO] --- maven-surefire-plugin:2.22.0:test (default-test) # playground.testng ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running TestSuite
test1
test2
test3
test4
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.758 s - in TestSuite
Some possible reasons why it fails in your case:
somehow the default behavior of preserve-order is overwritten
you call your tests in a way the testng.xml is not taken into account
I'm using JBehave and Maven to test a Spring MVC application. I am running the code below with a single story file. My problem is that I constantly get a StoryExecutionFailed error and I don't know why or how to fix it.
There is something suspicious with the way I am configuring JBehave, because I don't see some of my options actually being printed to output (example: output shows default timeout of 300 seconds but I've clearly set it to 10000 in code). Yet my story class is indeed running, because I see output printed to screen if I add System.out.println()'s. I am also suspicious that the story steps are not being mapped, because usually I'd see the steps code printed in output.
I'm hoping someone can help troubleshoot, because I don't know where to begin debugging this.
What I have checked so far:
Story text matches the annotations in my step class
Class qualifier in the spring context matches the actual class qualifier
Spring Annotations are in the right places (#Component)
Story paths are not null or empty (I printed these out in the storyPaths() method, printing omitted from this post)
EDIT: I have tried attaching Eclipse to a remote-debug session as outlined here, but even though maven waits for it to attach none of my breakpoints stop execution.
I start my tests like this:
mvn clean package
The error I see is this:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.mycompany.myproject.test.behavior.stories.APIStories
Processing system properties {}
Using controls EmbedderControls[batch=false,skip=false,generateViewAfterStories=true,ignoreFailureInStories=false,ignoreFailureInView=false,verboseFailures=false,verboseFiltering=false,storyTimeouts=300,threads=1,failOnStoryTimeout=false]
Running story stories/PROJ/PROJ-689.story
Using timeout for story PROJ-689.story of 300 secs.
Generating reports view to 'C:\Users\acymmer\Projects\myproject\target\jbehave' using formats '[ide_console, html, stats]' and view properties '{navigator=ftl/jbehave-navigator.ftl, views=ftl/jbehave-views.ftl, reports=ftl/jbehave-reports.ftl, nonDecorated=ftl/jbehave-report-non-decorated.ftl, decorated=ftl/jbehave-report-decorated.ftl, maps=ftl/jbehave-maps.ftl}'
Reports view generated with 0 stories (of which 0 pending) containing 0 scenarios (of which 0 pending)
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.584 sec <<< FAILURE! - in com.mycompany.myproject.test.behavior.stories.APIStories
run(com.mycompany.myproject.test.behavior.stories.APIStories) Time elapsed: 1.574 sec <<< ERROR!
org.jbehave.core.embedder.Embedder$RunningStoriesFailed: Failures in running stories:
stories/PROJ/PROJ-689.story: org.jbehave.core.embedder.StoryManager$StoryExecutionFailed: stories/PROJ/PROJ-689.story
at org.jbehave.core.embedder.Embedder$ThrowingRunningStoriesFailed.handleFailures(Embedder.java:553)
at org.jbehave.core.embedder.Embedder.handleFailures(Embedder.java:238)
at org.jbehave.core.embedder.Embedder.runStoriesAsPaths(Embedder.java:216)
at org.jbehave.core.junit.JUnitStories.run(JUnitStories.java:20)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
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:
APIStories>JUnitStories.run:20 ▒ RunningStoriesFailed Failures in running stor...
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.919 s
[INFO] Finished at: 2017-04-04T16:47:58-04:00
[INFO] Final Memory: 41M/374M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test (default-test) on project MyProject: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\acymmer\Projects\myproject\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
Scenario file text:
Scenario: Run a JBehave test successfully
Given this jbehave scenario
When mvn integration-test is run
Then expect success
Story class:
package com.mycompany.myproject.test.behavior.stories;
import static java.util.Arrays.asList;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.embedder.EmbedderControls;
import org.jbehave.core.failures.PassingUponPendingStep;
import org.jbehave.core.failures.PendingStepStrategy;
import org.jbehave.core.i18n.LocalizedKeywords;
import org.jbehave.core.io.CodeLocations;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.io.StoryLoader;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.model.ExamplesTableFactory;
import org.jbehave.core.parsers.RegexStoryParser;
import org.jbehave.core.reporters.Format;
import org.jbehave.core.reporters.StepdocReporter;
import org.jbehave.core.reporters.StoryReporter;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.ParameterControls;
import org.jbehave.core.steps.ParameterConverters;
import org.jbehave.core.steps.ParameterConverters.DateConverter;
import org.jbehave.core.steps.ParameterConverters.ExamplesTableConverter;
import org.jbehave.core.steps.spring.SpringApplicationContextFactory;
import org.jbehave.core.steps.spring.SpringStepsFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import com.mycompany.myproject.test.behavior.infrastructure.JiraCredentials;
import com.jbehaveforjira.javaclient.JiraStepDocReporter;
import com.jbehaveforjira.javaclient.JiraStoryReporter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Configuration for running JBehave stories.
* This class contains configuration for running stories and reporting results to Jira.
*/
#ContextConfiguration("classpath*:jbehave-app-context.xml")
#RunWith(SpringJUnit4ClassRunner.class)
public class APIStories extends JUnitStories {
private JiraCredentials jiraCredentials = new JiraCredentials();
public APIStories() { }
#Override
public Configuration configuration() {
ParameterConverters parameterConverters = new ParameterConverters();
ExamplesTableFactory examplesTableFactory = new ExamplesTableFactory(
new LocalizedKeywords(),
new LoadFromClasspath(this.getClass()),
parameterConverters);
parameterConverters.addConverters(
new DateConverter(new SimpleDateFormat("yyyy-MM-dd")),
new ExamplesTableConverter(examplesTableFactory));
return new MostUsefulConfiguration()
.useStoryReporterBuilder(CreateStoryReportBuilder())
.useStoryParser(new RegexStoryParser(examplesTableFactory))
.useStoryLoader(CreateStoryLoader())
.useStepdocReporter(CreateStepdocReporter())
.useParameterControls(CreateParameterControls())
.useParameterConverters(parameterConverters)
.usePendingStepStrategy(new PassingUponPendingStep());
}
#Override
public InjectableStepsFactory stepsFactory() {
ApplicationContext appContext = new SpringApplicationContextFactory("jbehave-app-context.xml")
.createApplicationContext();
return new SpringStepsFactory(configuration(), appContext);
}
#Override
protected List<String> storyPaths() {
return new StoryFinder().findPaths(
CodeLocations.codeLocationFromClass(this.getClass()).getFile(),
asList("**/" + System.getProperty("storyFilter", "*") + ".story"),
null); //no excludes
}
private StoryReporterBuilder CreateStoryReportBuilder() {
StoryReporterBuilder b = new StoryReporterBuilder() {
public StoryReporter reporterFor(String storyPath, org.jbehave.core.reporters.Format format) {
if (format.equals(org.jbehave.core.reporters.Format.HTML)) {
return new JiraStoryReporter(
new File("target", "story_report.xml"),
keywords(),
jiraCredentials.GetUrl(),
jiraCredentials.GetProject(),
jiraCredentials.GetUserName(),
jiraCredentials.GetPassword(),
jiraCredentials.GetEnvironment());
} else {
return super.reporterFor(storyPath, format);
}
}
};
b = b.withCodeLocation(CodeLocations.codeLocationFromClass(this.getClass()))
.withFailureTrace(true)
.withFormats(Format.IDE_CONSOLE, Format.HTML, Format.STATS);
return b;
}
public StoryLoader CreateStoryLoader() {
return new LoadFromClasspath(APIStories.class);
}
public StepdocReporter CreateStepdocReporter() {
return new JiraStepDocReporter(
jiraCredentials.GetUrl(),
jiraCredentials.GetProject(),
jiraCredentials.GetUserName(),
jiraCredentials.GetPassword());
}
public EmbedderControls CreateEmbedderControls() {
return new EmbedderControls()
.doSkip(true) //allows use of the #skip meta annotation on stories?
.doIgnoreFailureInStories(false)
.doIgnoreFailureInView(true)
.doGenerateViewAfterStories(true)
.doVerboseFailures(true)
.doVerboseFiltering(true)
.useStoryTimeouts("10000"); //temporarily ensure timeouts are not an issue
}
public ParameterControls CreateParameterControls() {
return new ParameterControls().useDelimiterNamedParameters(true);
}
}
Relevant bits from my POM (note that we are using this in the Test scope, in the same module as the actual application):
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<scope>test</scope>
<testSourceDirectory>${basedir}/src/test/java/</testSourceDirectory>
<testClassesDirectory>${project.build.directory}/test-classes/</testClassesDirectory>
<includes>
<include>com/mycompany/myproject/test/behavior/stories/*.java</include>
</includes>
<printSummary>true</printSummary>
</configuration>
</plugin>
...
<plugin>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-maven-plugin</artifactId>
<version>4.0.4</version>
<configuration>
<scope>test</scope>
</configuration>
<executions>
<execution>
<id>run-stories</id>
<phase>integration-test</phase>
<configuration>
<scope>test</scope>
<includes>
<include>com/mycompany/myproject/test/behavior/stories/*.java</include>
</includes>
<systemProperties>
<property>
<name>java.awt.headless</name>
<value>true</value>
</property>
</systemProperties>
<threads>1</threads>
<skip>false</skip>
<metaFilters>
<metaFilter>-skip</metaFilter>
</metaFilters>
</configuration>
<goals>
<goal>run-stories-as-embeddables</goal>
</goals>
</execution>
<execution>
<id>report-stepdocs</id>
<phase>integration-test</phase>
<configuration>
<includes>
<include>com/mycompany/myproject/test/behavior/stories/*.java</include>
</includes>
</configuration>
<goals>
<goal>report-stepdocs-as-embeddables</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>compile</scope>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
My Spring configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- =============================================================================================================== -->
<context:annotation-config />
<context:component-scan base-package="com.mycompany.myproject.test.behavior" />
</beans>
And finally my steps class:
#Component
public class EmptyJBehaveSteps {
#BeforeStory
public void BeforeStoryStarts() { }
#Given("this jbehave scenario")
public void Given() { }
#When("mvn integration-test is run")
public void When() { }
#Then("expect success")
public void Then() { }
#AfterStory
public void AfterStoryEnds() { }
}
use maven-surefire-plugin version 2.19.1, add this code <version>2.19.1</version> into maven-surefire-plugin. If you want to install the lib anyway you can run mvn clean install -DskipTests. and Right Click on project -> "Run as Maven Test". This will automatically download the missing plugin. & after that, Right Click on project ->"Update Maven project" it removes the error
I need to be able to use the profile activated during the run time of JUnit tests.
I was wondering if there is any way of doing something like:
String str = System.getProperty("activated.profile[0]");
Or any other relative way...
I realized there is an option to use ${project.profiles[0].id} bu somehow it's not working.
Any ideas?
When using surefire to run the unit tests, it usually spawns a new JVM to run the tests, and we have to pass the information to the new JVM. This can be done usually using the "systemPropertyVariables" tag.
I was able to exercise this using a quickstart Java project, where I added this to the POM:
I declared the following profiles
<profiles>
<profile>
<id>special-profile1</id>
</profile>
<profile>
<id>special-profile2</id>
</profile>
</profiles>
And this to surefire configuration:
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<systemPropertyVariables>
<profileId>${project.activeProfiles[0].id}</profileId>
</systemPropertyVariables>
</configuration>
</plugin>
...
</plugins>
</build>
And in my unit test, I added this:
/**
* Rigourous Test :-)
*/
public void testApp()
{
System.out.println("Profile ID: " + System.getProperty("profileId"));
}
When invoking the "test" command without profile (i.e. using mvn test), I got this:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.fxs.AppTest
Profile ID: development
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 sec - in com.fxs.AppTest
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
And we I used mvn -P special-profile2 test, I got this
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.fxs.AppTest
Profile ID: special-profile2
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec - in com.fxs.AppTest
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
This will pass along the name of the first active profile. If we have potentially more than one active profiles, then we will probably need to use more system properties.
Note: I tested this using Maven 3.1.1
I other cases I used next in pom file:
<profiles>
<profile>
<id>a-profile-id</id>
<properties>
<flag>a-flag-value</flag>
</properties>
</profile>
</profiles>
and in java:
String flagValue = System.getenv("flag");
I am trying to launch a Scage Project. I never used maven before.
I created a pom.xml file and downloaded the files with intellij
<?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>
<groupId>ScageTest</groupId>
<artifactId>ScageTest</artifactId>
<version>1.0</version>
<repositories>
<repository>
<id>scage</id>
<name>Scage Maven Repo</name>
<url>http://scage.googlecode.com/svn/maven-repository</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>su.msk.dunno</groupId>
<artifactId>scage</artifactId>
<version>0.9</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
This worked just fine. I also created the main file, as pointed in the tutorial
import net.scage.ScageScreenApp
import net.scage.ScageLib._
import net.scage.support.Vec
object HelloWorldExample extends ScageScreenApp("Hello World") {
private var ang = 0f
actionStaticPeriod(100) {
ang += 5
}
backgroundColor = BLACK
render {
openglMove(windowSize/2)
openglRotate(ang)
print("Hello World!", Vec(-50, -5), GREEN)
}
}
As pointed in the tutorial I have to use this command to build it mvn clean package -Pwebstart
log:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] --- maven-jar-plugin:2.3.2:jar (default-jar) # ScageTest ---
[WARNING] JAR will be empty - no content was marked for inclusion!
[INFO] Building jar: C:\Users\kanta\IdeaProjects\ScageTest\target\ScageTest-1.0.
jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.922s
[INFO] Finished at: Mon Oct 29 23:40:07 CET 2012
[INFO] Final Memory: 4M/15M
[INFO] ------------------------------------------------------------------------
[WARNING] The requested profile "webstart" could not be activated because it doe
s not exist.
Now the output is a .jar file instead of a .jnlp file, also nothing happens if I doubleclick the .jar file.
Any ideas what went wrong?
You are missing the webstart profile in your pom.xml
look at the pom.xml inside the scage example project: https://code.google.com/p/scage/downloads/detail?name=scage-example-project.zip&can=2&q=
it is quite large, but among others has thing it has the profile specified
<project>
<profiles>
<profile>
<id>webstart</id>
...
</profile>
</profiles>
</project>