JBehave Maven RunningStoriesFailed exception - java

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

Related

Unable to control parallel execution for cucumber

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"

Exception (stacktrace) not available in springboot unit test

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>

ClassNotFoundException error when trying to run java project using maven

In order to execute a java project using maven, I put on the terminal this two commands:
To build project:
mvn package
To run project:
mvn exec:java
The build always execute with success, but every time I try to run the project, I receive this error:
java.lang.ClassNotFoundException: com.pipa.api.Application
at java.net.URLClassLoader.findClass (URLClassLoader.java:471)
at java.lang.ClassLoader.loadClass (ClassLoader.java:588)
at java.lang.ClassLoader.loadClass (ClassLoader.java:521)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:281)
at java.lang.Thread.run (Thread.java:834)
Do you know what may be happening?
This is my Application.java file, with main function inside
package com.pipa.api;
import com.pipa.api.handlers.FetchUserPositionHandler;
import com.pipa.api.handlers.HighScoreHandler;
import com.pipa.api.handlers.ScoreRegisterHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
public class Application {
public static void main(String[] args) throws IOException {
int serverPort = 8000;
HttpServer server = HttpServer.create(new InetSocketAddress(serverPort), 0);
server.createContext("/", new FetchUserPositionHandler());
server.createContext("/highscorelist", new HighScoreHandler());
server.createContext("/score", new ScoreRegisterHandler());
server.setExecutor(null);
server.start();
}
}
This is my pom.xml
<groupId>com.pipa.httpserver</groupId>
<artifactId>pipa</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<mainClass>com.pipa.api.Application</mainClass>
</configuration>
</plugin>
</plugins>
</build>
I finally did this works. I discover that I need to put main / java right after src, on my project folder structure, following the pattern that maven uses. I did not notice, but even that my build command was working, my .jar file was been generated empty.

"Parameter 'browser' is required by BeforeClass on method beforeClass but has not been marked #Optional or defined" error in maven project

I have a maven project where in I am running testng.xml from pom.xml file.
My testng.xml file looks like below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests">
<test name="FirefoxTest">
<parameter name="browser" value="firefox"/>
<classes>
<class name="tests.PM_User_Test"/>
</classes>
</test> <!-- Test -->
<test name="ChromeTest">
<parameter name="browser" value="chrome"/>
<classes>
<class name="tests.PM_User_Test"/>
<class name="tests.PM_Extension_Test"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
and below is my class:
package base;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import utilities.ExcelReadAndWrite;
import utilities.Take_Screenshot;
public class ConfigClass
{
public WebDriver driver = null;
public static String excelPath = null;
public static ExcelReadAndWrite loginData;
public static ExcelReadAndWrite pmTests;
public static ExcelReadAndWrite snmTests;
public static ExcelReadAndWrite ipData;
#BeforeSuite
public void beforeSuite()
{
excelPath = "C://Users//mallikar//git//PM//PM//src//main//java//myTestData//TestData.xlsx";
loginData = new ExcelReadAndWrite("logindata", excelPath);
pmTests = new ExcelReadAndWrite("PMTestData", excelPath);
snmTests = new ExcelReadAndWrite("SNMTestData", excelPath);
ipData = new ExcelReadAndWrite("IP", excelPath);
}
#AfterSuite
public void afterSuite()
{
}
#Parameters({"browser"})
#BeforeClass
public void beforeClass(String browser)
{
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);
if(browser.equalsIgnoreCase("firefox"))
{
driver = new FirefoxDriver(dc);
}
else if(browser.equalsIgnoreCase("chrome"))
{
driver = new ChromeDriver();
}
}
/*#Parameters("browser")
#BeforeClass
public void beforeClass()
{
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);
driver = new FirefoxDriver(dc);
}*/
#AfterClass
public void afterClass()
{
driver.close();
}
#BeforeMethod
public void beforeMethod()
{
// driver.get("https://sqa.stackexchange.com/questions/36253/taking-screenshot-on-test-failure-selenium-webdriver-testng");
// System.out.println(driver);
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
#AfterMethod
public void afterMethod(ITestResult result) throws IOException
{
if(result.getStatus() == 2)
{
String methodName = result.getMethod().getMethodName();
new Take_Screenshot().get_Screenshot(driver, methodName);
}
}
}
But I am getting the "Parameter 'browser' is required by BeforeClass on method beforeClass but has not been marked #Optional or defined" error in maven project.
However when I run only testng.xml file it is absolutely working fine. The pro
blem comes when I run testng.xml from pom.xml file.
Below is the content of POM.xml file where I have defined testng.xml:
<profiles>
<profile>
<id>Regression</id>
<build>
<plugins>
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.2</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
I have gone through lot of threads about this on internet but I haven't found any solution. Please somebody help me with this.
And below are the console logs when I run mvn clean install command
Running TestSuite
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNG652Configurator#ba4d54
Tests run: 10, Failures: 2, Errors: 0, Skipped: 8, Time elapsed: 2.368 sec <<< FAILURE!
beforeClass(tests.PM_Extension_Test) Time elapsed: 2.098 sec <<< FAILURE!
org.testng.TestNGException:
Parameter 'browser' is required by BeforeClass on method beforeClass but has not been marked #Optional or defined
at org.testng.internal.Parameters.createParams(Parameters.java:289)
at org.testng.internal.Parameters.createParametersForMethod(Parameters.java:377)
at org.testng.internal.Parameters.createParameters(Parameters.java:721)
at org.testng.internal.Parameters.createConfigurationParameters(Parameters.java:164)
at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:275)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:176)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:122)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.testng.TestRunner.privateRun(TestRunner.java:770)
at org.testng.TestRunner.run(TestRunner.java:591)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:402)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:396)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:355)
at org.testng.SuiteRunner.run(SuiteRunner.java:304)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
at org.testng.TestNG.runSuites(TestNG.java:1032)
at org.testng.TestNG.run(TestNG.java:1000)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:77)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeMulti(TestNGDirectoryTestSuite.java:159)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:99)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:106)
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.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
beforeClass(tests.PM_User_Test) Time elapsed: 0.002 sec <<< FAILURE!
org.testng.TestNGException:
Parameter 'browser' is required by BeforeClass on method beforeClass but has not been marked #Optional or defined
at org.testng.internal.Parameters.createParams(Parameters.java:289)
at org.testng.internal.Parameters.createParametersForMethod(Parameters.java:377)
at org.testng.internal.Parameters.createParameters(Parameters.java:721)
at org.testng.internal.Parameters.createConfigurationParameters(Parameters.java:164)
at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:275)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:176)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:122)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.testng.TestRunner.privateRun(TestRunner.java:770)
at org.testng.TestRunner.run(TestRunner.java:591)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:402)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:396)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:355)
at org.testng.SuiteRunner.run(SuiteRunner.java:304)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
at org.testng.TestNG.runSuites(TestNG.java:1032)
at org.testng.TestNG.run(TestNG.java:1000)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:77)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeMulti(TestNGDirectoryTestSuite.java:159)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:99)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:106)
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.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Results :
Failed tests: beforeClass(tests.PM_Extension_Test): (..)
beforeClass(tests.PM_User_Test): (..)
Tests run: 10, Failures: 2, Errors: 0, Skipped: 8
[WARNING] Could not delete temp direcotry C:\Users\mallikar\git\PM\PM\target\surefire because Directory C:\Users\mallikar\git\PM\PM\target\surefire unable to be deleted.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.374 s
[INFO] Finished at: 2019-09-26T16:39:22+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project PM: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\mallikar\git\PM\PM\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
Please try doing one of the following (which should fix your problem )
Make sure that the annotation #Parameters is imported from the package org.testng.annotations
Make sure you adhere to one of the following, when running the test:
If you are running from the IDE, by right clicking on the class and choosing run as TestNG test then make sure that you edit your run configuration and provide the JVM argument -Dbrowser=firefox
If you would like to run the entire suite, then you would need to make sure that you right click on the suite and then run it.
If you are running from the commandline using maven, then make sure that you are using mvn clean test -P Regression (This would ensure that the profile Regression gets activated and through that, the test execution happens via the suite file)
For me adding configuration for xml suite inside maven-surefire-plugin worked.
I have added the below configuration.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.2</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>location-to-testng-xml-file</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>

Very simple step by step JBehave setup tutorial?

Though I have read many, but many articles on how to use JBehave, I can't get it to work. Here are the steps I went through so far:
Created new Java Project
Downloaded JBehave JAR file version 3.6.8 and added it to my build path libraries
Created a package called com.wmi.tutorials.bdd.stack.specs under the test source folder in my workspace
Added the JBehave JAR file to my Build path Library configuration
Created a JBehave story in the above-mentioned package (StackBehaviourStories.story)
Created a Java class in the above-mentioned package (StackBehaviourStory.java)
Created a Java class in the above-mentioned package (StackBehaviourSteps.java)
Imported the Given, Named, Then, When annotations in my Java class
Written two different scenarios in my JBehave story file
And still, I can't get it to work/run! =(
The story file:
Narrative:
In order to learn to with JBehave using Eclipse
As a junior Java developer though senior in .Net and in BDD
I want to define the behaviour of a custom stack
Scenario: I push an item onto the stack
Given I have an empty stack
When I push an item 'orange'
Then I should count 1
Scenario: I pop from the stack
Given I have an empty stack
When I push an item 'apple'
And I pop the stack
Then I should count 0
The story class
package com.wmi.tutorials.bdd.stack.specs
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.junit.JUnitStory;
public class StackBehaviourStory extends JUnitStory {
#Override
public Configuration configuration() { return new MostUsefulConfiguration(); }
#Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration()
, new StackBehaviourSteps());
}
}
The steps class
package com.wmi.tutorials.bdd.stack.specs
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import org.jbehave.core.junit.Assert;
public class StackBehaviourSteps {
#Given("I have an empty stack")
public void givenIHaveAnEmptyStack() { stack = new CustomStack(); }
#When("I push an item $item")
public void whenIPushAnItem(#Named("item") String item) { stack.push(item); }
#Then("I should count $expected")
public void thenIShouldCount(#Named("expected") int expected) {
int actual = stack.count();
if (actual != expected)
throw new RuntimeException("expected:"+expected+";actual:"+actual);
}
}
I'm currently using Eclipse Kepler (4.3) JEE with everything I need to use JUnit, Google App Engine, and yes, JBehave is installed correctly following the Eclipse JBehave installation tutorial.
I can't get it to work. So how can I make it work correctly using Eclipse, JBehave and JUnit?
I know I'm late to the party here but I'm posting because this is the info I wish I had a week ago as it would've saved me a lot of pain. I'm very much into the idea of BDD, but am unfortunately finding JBehave's docs to be a bit of a nightmare, especially when it comes to Maven integration. Moreover a lot of the code I found both on their website and elsewhere didn't work. Through trial and error, and lots of tutorials, I was able to piece together the following. It runs both in Maven and Eclipse, has a single binding class that maps stories to step files, and is able to find story files located in src/test/resources.
here is a working pom file:
<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.projectvalis.st1</groupId>
<artifactId>st1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>st1</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgument></compilerArgument>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${failsafe.and.surefire.version}</version>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
<plugin>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-maven-plugin</artifactId>
<version>4.0.2</version>
<executions>
<execution>
<id>run-stories-as-embeddables</id>
<phase>integration-test</phase>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
<ignoreFailureInStories>false</ignoreFailureInStories>
<ignoreFailureInView>false</ignoreFailureInView>
<systemProperties>
<property>
<name>java.awt.headless</name>
<value>true</value>
</property>
</systemProperties>
</configuration>
<goals>
<goal>run-stories-as-embeddables</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-core</artifactId>
<version>4.0.2</version>
</dependency>
</dependencies>
</project>
here is a sample story file
Narrative:
In order to work with files to compress
As a guy who wants to win a bet with cameron
I want to ensure files are ingested and processed in the manner in which the
methods in the ingest class purport to process them.
Scenario: Simple test to give JBehave a test drive
Given a file, a.log
When the caller loads the file as a byte array
Then the byte array that is returned contains the correct number of bytes.
here is a sample step file
package com.projectvalis.compUtils.tests.ingest;
import java.io.File;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import org.jbehave.core.steps.Steps;
import org.junit.Assert;
import com.projectvalis.compUtils.util.fileIO.Ingest;
/**
* BDD tests for the ingest class
* #author funktapuss
*
*/
public class LoadByteSteps extends Steps {
private String fNameS;
private byte[] byteARR;
#Given("a file, $filename")
public void setFileName(#Named("filename") String filename) {
File file = new File(getClass().getResource("/" + filename).getFile());
fNameS = file.getPath();
}
#When("the caller loads the file as a byte array")
public void loadFile() {
byteARR = Ingest.loadFile(fNameS);
}
#Then("the byte array that is returned contains the "
+ "correct number of bytes.")
public void checkArrSize() {
File file = new File(fNameS);
Assert.assertTrue(
"loading error - "
+ "the file and the resultant byte array are different sizes!",
(long)byteARR.length == file.length());
}
}
and here is the generic runner
package com.projectvalis.compUtils.tests.runner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.io.CodeLocations;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.Format;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.jbehave.core.steps.Steps;
import com.projectvalis.compUtils.tests.ingest.LoadByteSteps;
/**
* generic binder for all JBehave tests. Binds all the story files to the
* step files. works for both Eclipse and Maven command line build.
* #author funktapuss
*
*/
public class JBehaveRunner_Test extends JUnitStories {
#Override
public Configuration configuration() {
return new MostUsefulConfiguration()
.useStoryLoader(
new LoadFromClasspath(this.getClass().getClassLoader()))
.useStoryReporterBuilder(
new StoryReporterBuilder()
.withDefaultFormats()
.withFormats(Format.HTML, Format.CONSOLE)
.withRelativeDirectory("jbehave-report")
);
}
#Override
public InjectableStepsFactory stepsFactory() {
ArrayList<Steps> stepFileList = new ArrayList<Steps>();
stepFileList.add(new LoadByteSteps());
return new InstanceStepsFactory(configuration(), stepFileList);
}
#Override
protected List<String> storyPaths() {
return new StoryFinder().
findPaths(CodeLocations.codeLocationFromClass(
this.getClass()),
Arrays.asList("**/*.story"),
Arrays.asList(""));
}
}
the runner lives in src/test/java//tests.runner.
the ingest test lives in src/test/java//tests.ingest.
the story files live in src/test/resources/stories.
As far as I can tell, JBehave has LOTS of options, so this certainly isn't the only way of doing things. Treat this like a template that will get you up and running quickly.
full source is on github.
Following step by step closely the jbehave Getting Started tutorial, the Run story section says: [...] the ICanToggleACell.java class will allow itself to run as a JUnit test.
This means that the JUnit library is required in your Build path.
Using Eclipse:
Select your current project and right-click it, Build path, Configure Build Path...
Properties for [current project], Java Build Path, Libraries, click [Add Library...]
Add Library, select JUnit, click [Next]
JUnit Library, JUnit library version, select the version you wish to use, click [Finish]
Java Build Path, click [OK]
Project Explorer, select your ICanToggleACell.java class, right-click it, then Run As, and click on JUnit Test
So this is the same here as for the above-example code. The StackBehaviourStory.java class should let itself run as a JUnit test after you add the proper library to the Java build path.
In my case, I have extended my Steps class from Steps (from jbehave core)
i had updated the JunitStory to JunitStories and it worked
public class StackBehaviourStory extends JUnitStory ---> JunitStories

Categories

Resources