JBehave Configuration Tutorial

50 Comments

I love JBehave. It’s a great test automation framework that takes full advantage of all the possibilities of the JVM and the plethora of libraries that are available for Java. JBehave makes the transition from natural language style BDD-tests to Java methods incredibly quick, it’s just an annotation away. But … I hate to say it, but there’s a big “BUT” here … it is more often than not a little bit too flexible and configurable. So much that you tend to lose overview and understand. This is why I would like to give you a hand and guide you through the first steps.

So, what does it take to do some test automation? Three things: a test, something that automates the test, and something that runs the test. So, let me present to you the simplest and shortest way to run a test with JBehave. I will then show step for step how to make the setup more flexible, and explain why you should do it.

JBehave KISSed

The Test

Scenario: 2 squared

Given a variable x with value 2
When I multiply x by 2 
Then x should equal 4

Scenario: 3 squared

Given a variable x with value 3
When I multiply x by 3 
Then x should equal 10

The test will stay the same for the rest of the examples. It’s quite forward, and there’s possible a mistake in one of the two scenarios.

Steps

The thingies necessary to let JBehave know what exactly it should do when it encounters “Given a variable x with value 2″ are called StepCandidates. The easiest way is to have a set of methods in a class and annotate them with @Given, @When or @Then.

package de.codecentric.simplejbehave._1_kiss;
 
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;
 
public class ExampleSteps extends Steps {
	int x;
 
	@Given("a variable x with value $value")
	public void givenXValue(@Named("value") int value) {
		x = value;
	}
 
	@When("I multiply x by $value")
	public void whenImultiplyXBy(@Named("value") int value) {
		x = x * value;
	}
 
	@Then("x should equal $value")
	public void thenXshouldBe(@Named("value") int value) {
		if (value != x)
			throw new RuntimeException("x is " + x + ", but should be " + value);
	}
}

Note that the class currently extends from Steps. This is necessary because of the way, we will use the steps and will become obsolete later. I’ll show You, just a second.

Test Execution

Missing now is only something that looks for the story test, finds the Steps and executes the test. So this is how you do that in the most simple way:

package de.codecentric.simplejbehave._1_kiss;
 
import java.util.Arrays;
import java.util.List;
 
import org.jbehave.core.embedder.Embedder;
 
public class SimpleJBehave {
 
	private static Embedder embedder = new Embedder();
	private static List<String> storyPaths = Arrays
			.asList("de/codecentric/simplejbehave/Math.story");
 
	public static void main(String[] args) {
		embedder.candidateSteps().add(new ExampleSteps());
		embedder.runStoriesAsPaths(storyPaths);
	}
}

You have a classic Java main method. It uses an Embedder, which is JBehave’s main entry point with a really bad name (But it is not alone with its fate of a badly chosen name, there are more in the flock of badly named classes in JBehave…) The Embedder is designed to embed JBehave in all sorts of IDEs, test frameworks, you name it. In our case, we embed JBehave in nothing, use it bare naked.

There are two things, that we have to tell JBehave. First: Where are your steps. For that, we add an instance of our class to the list of candidate steps. And then, we have to tell JBehave which story to run. This is as simple, as passing a list of strings to a method which runs that stories.

This is it. Don’t believe me? Try it out yourself, you should get this as an output:

Processing system properties {}
Using controls EmbedderControls[batch=false,skip=false,generateViewAfterStories=true,ignoreFailureInStories=false,ignoreFailureInView=false,verboseFailures=false,verboseFiltering=false,storyTimeoutInSecs=300,threads=1]
Running story de/codecentric/simplejbehave/Math.story
Generating reports view to 'C:\cc\workspace-git\SimpleJBehave\target\jbehave' using formats '[]' and view properties '{defaultFormats=stats, decorateNonHtml=true, viewDirectory=view, decorated=ftl/jbehave-report-decorated.ftl, reports=ftl/jbehave-reports-with-totals.ftl, maps=ftl/jbehave-maps.ftl, navigator=ftl/jbehave-navigator.ftl, views=ftl/jbehave-views.ftl, nonDecorated=ftl/jbehave-report-non-decorated.ftl}'
Reports view generated with 1 stories (of which 0 pending) containing 2 scenarios (of which 0 pending)
Exception in thread "main" org.jbehave.core.embedder.Embedder$RunningStoriesFailed: Failures in running stories: ReportsCount[stories=1,storiesNotAllowed=0,storiesPending=0,scenarios=2,scenariosFailed=1,scenariosNotAllowed=0,scenariosPending=0,stepsFailed=1]
	at org.jbehave.core.embedder.Embedder$ThrowingRunningStoriesFailed.handleFailures(Embedder.java:499)
	at org.jbehave.core.embedder.Embedder.handleFailures(Embedder.java:265)
	at org.jbehave.core.embedder.Embedder.generateReportsView(Embedder.java:252)
	at org.jbehave.core.embedder.Embedder.generateReportsView(Embedder.java:233)
	at org.jbehave.core.embedder.Embedder.runStoriesAsPaths(Embedder.java:212)
	at de.codecentric.simplejbehave._1_kiss.SimpleJBehave.main(SimpleJBehave.java:16)

Of course there is much defaulting now happening under the hood. We will come to that in a moment. For now you should remember, that JBehave basically needs two things: your tests and your steps. Everything else is just nice to make everything more flexible.

Skip the main, use JUnit

The first thing we want to get rid of is our own main method. We will rather use another class that comes with JBehave: JUnitStories. This class takes all the stories you pass in and runs them with JUnit. The benefit is, that there are many, many tools available integrate with JUnit (make it run, parse the result), which makes it my preferred way of running JBehave tests.

package de.codecentric.simplejbehave._2_junit;
 
import java.util.Arrays;
import java.util.List;
 
import org.jbehave.core.junit.JUnitStories;
 
public class SimpleJBehave extends JUnitStories {
 
	public SimpleJBehave() {
		super();
		this.configuredEmbedder().candidateSteps().add(new ExampleSteps());
	}
 
	@Override
	protected List<String> storyPaths() {
		return Arrays.asList("de/codecentric/simplejbehave/Math.story");
	}
}

What has changed? We extend from JUnitStories. For that we have to implement an abstract method storyPaths that returns all our tests. So we have our stories covered. What was the other thing JBehave needs? Our steps. Right. There’s still an Embedder hidden in the JUnitStories, and we can get to it via the configuredEmbedder() method.

Apart from that, we changed nothing, but can now use JUnit to run our test. Awesome!

Ok, I see what you are seeing. Just having a single run method for all the tests there, is not what you want. I agree, and there’s a solution.

Introducing a StepsFactory

In order to make that solution work, we should use a more conventional way of providing the steps to JBehave. Usually you don’t force them down to JBehave by adding them to the embedder, but you provide a steps factory. This has the advantage that you can later use dependency injection frameworks like Spring or Guice to wire your step classes. But I am running ahead. With the introduction of the step factory, two things change: We can get rid of extending from Step in our Steps:

package de.codecentric.simplejbehave._3_stepsfactory;
 
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
 
public class ExampleSteps {
	int x;
 
	@Given("a variable x with value $value")
	public void givenXValue(@Named("value") int value) {
		x = value;
	}
 
	@When("I multiply x by $value")
	public void whenImultiplyXBy(@Named("value") int value) {
		x = x * value;
	}
 
	@Then("x should equal $value")
	public void thenXshouldBe(@Named("value") int value) {
		if (value != x)
			throw new RuntimeException("x is " + x + ", but should be " + value);
	}
 
}

The class with the StepCandidates is now a true Plain Old Java Class. Yay :) Next, let JBehave know how to create new steps.

package de.codecentric.simplejbehave._3_stepsfactory;
 
import java.util.Arrays;
import java.util.List;
 
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.junit.runner.RunWith;
 
import de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner;
 
@RunWith(JUnitReportingRunner.class)
public class SimpleJBehave extends JUnitStories {
 
	public SimpleJBehave() {
		super();
	}
 
	@Override
	public InjectableStepsFactory stepsFactory() {
		return new InstanceStepsFactory(configuration(), new ExampleSteps());
	}
 
	@Override
	protected List<String> storyPaths() {
		return Arrays.asList("de/codecentric/simplejbehave/Math.story");
	}
}

The simplest InjectableStepsFactory class you can use is the InstanceStepsFactory, which you just have to provide with a list of objects that contain annotated methods. Another thing you have to pass into the steps factory is on ominous configuration. We will see in the next example what that is exactly, so for now, we just call a method from a super class and live with whatever configuration we get.

With all that setup, we can leverage a nice tool, that wires the JBehave monitoring capabilities together with JUnit notifications. It is called jbehave-junit-runner, and the only thing you have to do is to let JUnit know to use the class, by declaring it with the @RunWith annotation. In short you now get this as a result:

Now, wow, we could stop here. You can execute JBehave tests and can leverage all great JUnit accessories out there. But we don’t :)

MostUsefulConfiguration

One of the better named classes in JBehave is a subclass of Configuration named MostUsefulConfiguration. I will show you what are all the defaults that you get, when you don’t specify anything extraordinary, like we did so far. With this runner, you get the same result as above, but you have to write a lot more code :)

package de.codecentric.simplejbehave._4_configuration;
 
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
 
import org.jbehave...
 
import org.junit.runner.RunWith;
 
import com.thoughtworks.paranamer.NullParanamer;
 
import de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner;
 
@RunWith(JUnitReportingRunner.class)
public class SimpleJBehave extends JUnitStories {
 
	private Configuration configuration;
 
	public SimpleJBehave() {
		super();
		configuration = new Configuration() {
		};
 
		// configuration.doDryRun(false); "no dry run" is implicit by using
		// default StoryControls
 
		// configuration.useDefaultStoryReporter(new ConsoleOutput());
		// deprecated -- rather use StoryReportBuilder
 
		configuration.useFailureStrategy(new RethrowingFailure());
		configuration.useKeywords(new LocalizedKeywords(Locale.ENGLISH));
		configuration.usePathCalculator(new AbsolutePathCalculator());
		configuration.useParameterControls(new ParameterControls());
		configuration.useParameterConverters(new ParameterConverters());
		configuration.useParanamer(new NullParanamer());
		configuration.usePendingStepStrategy(new PassingUponPendingStep());
		configuration.useStepCollector(new MarkUnmatchedStepsAsPending());
		configuration.useStepdocReporter(new PrintStreamStepdocReporter());
		configuration.useStepFinder(new StepFinder());
		configuration.useStepMonitor(new SilentStepMonitor());
		configuration
				.useStepPatternParser(new RegexPrefixCapturingPatternParser());
		configuration.useStoryControls(new StoryControls());
		configuration.useStoryLoader(new LoadFromClasspath());
		configuration.useStoryParser(new RegexStoryParser(configuration
				.keywords()));
		configuration.useStoryPathResolver(new UnderscoredCamelCaseResolver());
		configuration.useStoryReporterBuilder(new StoryReporterBuilder());
		configuration.useViewGenerator(new FreemarkerViewGenerator());
 
		EmbedderControls embedderControls = configuredEmbedder()
				.embedderControls();
		embedderControls.doBatch(false);
		embedderControls.doGenerateViewAfterStories(true);
		embedderControls.doIgnoreFailureInStories(false);
		embedderControls.doIgnoreFailureInView(false);
		embedderControls.doSkip(false);
		embedderControls.doVerboseFailures(false);
		embedderControls.doVerboseFiltering(false);
		embedderControls.useStoryTimeoutInSecs(300);
		embedderControls.useThreads(1);
	}
 
	@Override
	public Configuration configuration() {
		return configuration;
	}
 
	@Override
	public InjectableStepsFactory stepsFactory() {
		return new InstanceStepsFactory(configuration(), new ExampleSteps());
	}
 
	@Override
	protected List<String> storyPaths() {
		return Arrays.asList("de/codecentric/simplejbehave/Math.story");
	}
}

Phew. That’s quite an amount of configuration to digest. And for that reason, we won’t digest it now, but in a later blog post. What I wanted to show you here, is all the possibilities that you have. Sometimes the effects and of the configuration are interlinked with each other. We will take a closer look into all that in the future. But for now remember this:

1) It is very important, that your overridden configuration() method always returns the same object. It’s used in multiple places in JBehave. Sometimes it is passed on and sometimes, somebody get’s a fresh instance by calling your method again. Make sure that you don’t run into inconsistencies.

2) There are two main points to configure the behaviour of JBehave. The embedderControls that control how the embedder itself is working. And the configuration that adjusts everything else. The distinction is now always clear. I’ll explain that better in the next blog post.

And with this, it is time to go out, try it for yourself and write some tests. Let me know if this helped you to better understand how JBehave works. It sure helped me, when I wrote the blog post.

Author

Andreas Ebbert-Karroum

Andreas Ebbert-Karroum

Share on FacebookGoogle+Share on LinkedInTweet about this on TwitterShare on RedditDigg thisShare on StumbleUpon

Kommentare

  • Thomas Jaspers

    Hi Andreas,

    great, as this is one of the things that is very much missing from our basic JBehave Tutorial. I have added a link from there to your article :-).

    Cheers
    – Thomas

  • July 3, 2012 von Joey

    Hi Andreas,
    Very useful. Is there a way to have the stories inputed be a StringBuffer? I’d like to read my test cases from a db and then pass it to jbehave rather than use a plain txt file

    • Andreas Ebbert-Karroum

      Hi Joey,

      thanks, glad you found the post useful. Writing it also helped me a lot to understand how JBehave works.

      You are asking an interesting question. I have not tried it myself, but loading stories is abstracted in the StoryLoader Interface. There are implementations available to load stories from an URL, so why not as well from a database.

      If you succeed, it’d be nice, if you blog about it, or let me know by other means, if it worked. I’m curious :)

      Kind Regards,
      Andreas

    • Hi Joey,
      I stumbled across your post saying how you were trying to load jBehave stories from a DB (presumably via a custom StoryLoader implementation). I’d like to do the same thing but am having trouble figuring out where to start. Were you successful?

      Thanks!
      Tom

  • July 5, 2012 von Keki

    Hi Andreas,
    I am trying to implement Jbehave using Webdriver in a very basic form it gives No class found error: transformer. my Glue code is as follows could you please help.

    public class LoginStepsGlue extends JUnitStories {

    private WebDriverProvider driverProvider = new PropertyWebDriverProvider();
    //private WebDriverSteps lifecycleSteps = new PerStoriesWebDriverSteps(driverProvider);
    private SeleniumContext context = new SeleniumContext();
    //private ContextView contextView = new LocalFrameContextView().sized(500, 100);
    public Configuration configuration;

    @Override
    public Configuration configuration() {
    return new SeleniumConfiguration().useSeleniumContext(context).useWebDriverProvider(driverProvider);

    }

    @Override
    public List candidateSteps() {
    return new InstanceStepsFactory(configuration(), new LoginSteps())
    .createCandidateSteps();

    }

    /* @Override
    public InjectableStepsFactory stepsFactory() {
    return new InstanceStepsFactory(configuration(), new LoginSteps());
    //new WebDriverScreenshotOnFailure(driverProvider, configuration.storyReporterBuilder());
    }*/

    @Override
    protected List storyPaths() {
    return Arrays.asList(“D:/Selenium/WorkFiles/EclipseCode/BDD/srcstories”);
    }

    }

    • Andreas Ebbert-Karroum

      Hi,

      first of all, I’m not a big fan of the WebDriverProvider, I see no added a value at all in comparison to using Selenium directly.

      Having that said, I don’t know why you get that exception. Could you post the complete Stacktrace? In addition, you don’t need the candidateSteps() method. As you see in my blog post above, which you have certainly read, the stepsFactory() is sufficient.

  • July 9, 2012 von Randy

    Hi Andreas,
    I never knew anything about JBehave or for that matter BDD, but now I do understand the base aspects of it. I do my automation tests using Junit and Selenium Webdriver. PLEASE if you could, my question is what necessary change should I be making to this part of the code
    private Configuration configuration;

    public SimpleJBehave() {
    super();
    configuration = new Configuration() {
    };
    do I save my story files with a .story extensions or without any extensions, and do I run my tests by right clicking on my story files as Junit tests? or is there a different way to do it.

  • July 19, 2012 von Glenn G

    Hi Andreas, thanks for the interesting tutorial.

    I’m getting the following error: java.lang.NoClassDefFoundError: org/apache/commons/collections/Transformer

    I have set-up the ExampleSteps.java & SimpleJBehave.java classes in an Eclipse package; I’ve copied exactly everything you’ve written, but I cannot seem to get rid of the above error. The JUnit report states that it’s an “initializationError”.

    I’m quite new to this and would really appreciate any guidance to resolve this issue, thanks in advance.

    • Andreas Ebbert-Karroum

      Hi Glenn,

      can you post the Stacktrace, where the NoClassDefFoundError results from? Otherwise it’s hard to debug that. Are you using Maven to manage all the dependencies?

      Andreas

      • July 20, 2012 von Glenn G

        Thanks for the quick reply,

        No I’m adding JARs to the class-path manually, I added the jbehave-core(3.6+), junit(4.10) and jbehave-junit-runner (1.0.1).

        I managed to get JUnit to show me the structure that you have showed in the screen shot above. Now I have a BeforeStories, Math.story and AfterStories showing up. But I’m getting the following error:

        Processing system properties {}
        Using controls EmbedderControls[batch=false,skip=false,generateViewAfterStories=true,ignoreFailureInStories=false,ignoreFailureInView=false,verboseFailures=false,verboseFiltering=false,storyTimeoutInSecs=300,threads=1]
        Running story com/simple/jbehave/Math.story
        Generating reports view to 'C:\Users\Glenn\Documents\workspace-sts-2.9.1.RELEASE\JBehaveConfigTut\target\jbehave' using formats '[junitscenarioreporter]' and view properties '{defaultFormats=stats, decorateNonHtml=true, viewDirectory=view, decorated=ftl/jbehave-report-decorated.ftl, reports=ftl/jbehave-reports-with-totals.ftl, maps=ftl/jbehave-maps.ftl, navigator=ftl/jbehave-navigator.ftl, views=ftl/jbehave-views.ftl, nonDecorated=ftl/jbehave-report-non-decorated.ftl}'
        Reports view generated with 0 stories (of which 0 pending) containing 0 scenarios (of which 0 pending)
        java.lang.RuntimeException: org.jbehave.core.embedder.Embedder$RunningStoriesFailed: Failures in running stories:
        com/simple/jbehave/Math.story: org.jbehave.core.embedder.StoryManager$StoryExecutionFailed: com/simple/jbehave/Math.story
        at de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner.run(JUnitReportingRunner.java:81)
        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: org.jbehave.core.embedder.Embedder$RunningStoriesFailed: Failures in running stories:
        com/simple/jbehave/Math.story: org.jbehave.core.embedder.StoryManager$StoryExecutionFailed: com/simple/jbehave/Math.story
        at org.jbehave.core.embedder.Embedder$ThrowingRunningStoriesFailed.handleFailures(Embedder.java:495)
        at org.jbehave.core.embedder.Embedder.handleFailures(Embedder.java:224)
        at org.jbehave.core.embedder.Embedder.runStoriesAsPaths(Embedder.java:205)
        at de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner.run(JUnitReportingRunner.java:79)
        ... 6 more

        • July 20, 2012 von Glenn G

          Okay, got the tests to pass (Scenario 3 was causing that error, as it was expecting 10 and ‘x’ was 9), but the HTML report is still showing 0 successful stories…

          In fact I am still getting the following to show up in the console:

          Reports view generated with 0 stories (of which 0 pending) containing 0 scenarios (of which 0 pending)

          Any ideas on how this is happening?

          • Andreas Ebbert-Karroum

            Getting the report generation right can be tricky. I’ll cover that in a later post.

            Andreas

          • March 21, 2013 von Roland

            For me, replacing the line
            configuration.useStoryReporterBuilder(new StoryReporterBuilder());
            with
            configuration.useStoryReporterBuilder(new StoryReporterBuilder().withFormats(Format.STATS));
            fills the stats line with some numbers…

      • May 8, 2013 von Alvaro

        hello I have the same problem , when exec the example I see this printstackTrace
        Exception in thread “main” java.lang.NoSuchFieldError: SHORT_PREFIX_STYLE
        at org.jbehave.core.embedder.EmbedderControls.toString(EmbedderControls.java:107)
        at java.lang.String.valueOf(Unknown Source)
        at java.lang.StringBuilder.append(Unknown Source)
        at org.jbehave.core.embedder.PrintStreamEmbedderMonitor.usingControls(PrintStreamEmbedderMonitor.java:176)
        at org.jbehave.core.embedder.Embedder.runStoriesAsPaths(Embedder.java:188)
        at com.sch.example.bdd.SimpleJBehave.main(SimpleJBehave.java:14)

  • Thank you so much for this article. It really helped a lot
    This is the article I really wanted to write about jbehave.
    A good starting point is always priceless.

  • December 11, 2012 von Shailesh

    Hi Andreas

    I am getting an error which says,

    Exception in thread “main” org.jbehave.core.embedder.Embedder$RunningStoriesFailed: Failures in running stories D:\SonnetTEST\jBehave\src\umm\softwaredesign\simplearithmetic\Math.story
    at org.jbehave.core.embedder.Embedder.runStoriesAsPaths(Embedder.java:213)
    at umm.softwaredesign.simplearithmetic.SimpleJBehave.main(SimpleJBehave.java:16)
    Caused by: org.jbehave.core.io.StoryResourceNotFound: Story path ‘D:\SonnetTEST\jBehave\src\umm\softwaredesign\simplearithmetic\Math.story’ not found by class loader sun.misc.Launcher$AppClassLoader@35ce36
    at org.jbehave.core.io.LoadFromClasspath.loadResourceAsText(LoadFromClasspath.java:32)
    at org.jbehave.core.io.LoadFromClasspath.loadStoryAsText(LoadFromClasspath.java:42)
    at org.jbehave.core.embedder.StoryRunner.storyOfPath(StoryRunner.java:84)
    at org.jbehave.core.embedder.Embedder.runStoriesAsPaths(Embedder.java:203)
    … 1 more

    I am new to JBehave, please help.

    • Andreas Ebbert-Karroum

      Hi Shailesh,

      it’d be helpful if you not only post the output, but also your sources and how you run JBehave.

      Andreas

    • December 11, 2012 von Shailesh

      the above issue has been resolved, but i am getting another issue i have tried with both freemaker-2.2.5.jar and freemaker-2.3.18.jar and i am getting an error as

      Exception in thread “main” org.jbehave.core.embedder.Embedder$ViewGenerationFailed: View generation failed to D:\SonnetTEST\jBehave\target\jbehave for formats [] and resources {defaultFormats=stats, decorateNonHtml=true, viewDirectory=view, decorated=ftl/jbehave-report-decorated.ftl, reports=ftl/jbehave-reports-with-totals.ftl, maps=ftl/jbehave-maps.ftl, navigator=ftl/jbehave-navigator.ftl, views=ftl/jbehave-views.ftl, nonDecorated=ftl/jbehave-report-non-decorated.ftl}
      at org.jbehave.core.embedder.Embedder.generateReportsView(Embedder.java:360)
      at org.jbehave.core.embedder.Embedder.generateReportsView(Embedder.java:344)
      at org.jbehave.core.embedder.Embedder.runStoriesAsPaths(Embedder.java:231)
      at SimpleJBehave.main(SimpleJBehave.java:16)
      Caused by: org.jbehave.core.reporters.TemplateableViewGenerator$ReportCreationFailed: Report creation failed from file {umm.softwaredesign.simplearithmetic.i_can_toggle_a_cell=[D:\SonnetTEST\jBehave\target\jbehave\umm.softwaredesign.simplearithmetic.i_can_toggle_a_cell.stats]}
      at org.jbehave.core.reporters.TemplateableViewGenerator.createReports(TemplateableViewGenerator.java:184)
      at org.jbehave.core.reporters.TemplateableViewGenerator.generateReportsView(TemplateableViewGenerator.java:111)
      at org.jbehave.core.embedder.Embedder.generateReportsView(Embedder.java:357)
      … 3 more
      Caused by: org.jbehave.core.reporters.TemplateableViewGenerator$ViewGenerationFailedForTemplate: ftl/jbehave-report-decorated.ftl
      at org.jbehave.core.reporters.TemplateableViewGenerator.write(TemplateableViewGenerator.java:228)
      at org.jbehave.core.reporters.TemplateableViewGenerator.createReports(TemplateableViewGenerator.java:177)
      … 5 more
      Caused by: org.jbehave.core.reporters.FreemarkerProcessor$FreemarkerProcessingFailed: Freemarker failed to process template ftl/jbehave-report-decorated.ftl using configuration freemarker.template.Configuration@1e9cb75 and data model {body=, name=umm.softwaredesign.simplearithmetic.i_can_toggle_a_cell, format=stats}
      at org.jbehave.core.reporters.FreemarkerProcessor.process(FreemarkerProcessor.java:16)
      at org.jbehave.core.reporters.TemplateableViewGenerator.write(TemplateableViewGenerator.java:225)
      … 6 more
      Caused by: freemarker.template.ParseException: Encountered “true” at line 1, column 24.
      Was expecting:

      at freemarker.template.FMParser.generateParseException(FMParser.java:3869)
      at freemarker.template.FMParser.jj_consume_token(FMParser.java:3747)
      at freemarker.template.FMParser.HeaderElement(FMParser.java:2309)
      at freemarker.template.FMParser.Root(FMParser.java:2369)
      at freemarker.template.Template.(Template.java:132)
      at freemarker.cache.TemplateCache.loadTemplate(TemplateCache.java:359)
      at freemarker.cache.TemplateCache.getTemplate(TemplateCache.java:330)
      at freemarker.template.Configuration.getTemplate(Configuration.java:446)
      at freemarker.template.Configuration.getTemplate(Configuration.java:411)
      at org.jbehave.core.reporters.FreemarkerProcessor.process(FreemarkerProcessor.java:14)
      … 7 more

      plz help

      • December 11, 2012 von Shailesh

        Hi Andreas thanks for the reply i am running JBehave on Eclipse, and i am running your sample code only (which is at the top of this webpage)

  • January 4, 2013 von chand

    i was able to run multiple stories with multile
    classes and one one configuaration class.

    now i want to use cross reference to allow output
    in json and xml formats.

    i am using the below code
    and getting the exception as no class definition
    found -com\thoughtworks\xtream\Heirarchial

    package sample_without_steps;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.util.ArrayList;
    import java.util.List;
    import org.jbehave.core.configuration.Configuration;
    import org.jbehave.core.configuration.MostUsefulConfiguration;
    import org.jbehave.core.junit.JUnitStories;
    import org.jbehave.core.reporters.CrossReference;
    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.junit.runner.RunWith;
     
     
    import de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner;
     
    @RunWith(JUnitReportingRunner.class)
    public class SimpleJBehave1 extends JUnitStories {
    	CrossReference xref = new CrossReference();
    	public  SimpleJBehave1() {
    		super();
    	}
     
    	@Override
    	public InjectableStepsFactory stepsFactory() {
    		return new InstanceStepsFactory(configuration(), new ExampleSteps(),new ExampleSteps1());
    	}
     
    	@Override
    	public Configuration configuration() {
     
    		return new MostUsefulConfiguration()             // CONSOLE and HTML reporting
    		.useStoryReporterBuilder(new StoryReporterBuilder()
    			.withFormats(Format.CONSOLE,Format.HTML,Format.XML).withCrossReference(xref)); 
    		//.withDefaultFormats().
    		/*.withCrossReference(xref))
            .useStepMonitor(xref.getStepMonitor());*/
    	}
     
     
     
    	@Override
    	protected List storyPaths() {
     
    		/*ff f1=new ff();
    		List  s1= f1.fileread();
    		return s1;*/
    		List list = new ArrayList();;
    		try
    		{
    			FileReader reader = new FileReader("C:/a.txt");
    	     BufferedReader br = new BufferedReader(reader);
    	     String str=null;
    	     while ((str = br.readLine()) != null) {
    	        	     list.add(str);      	  
    	     }
    	     System.out.println(list);
     
    	     reader.close();
    	    }catch (Exception e){//Catch exception if any
    	  System.err.println("Error: " + e.getMessage());
    	  }
    	    return list;
     
    	}
    }
  • January 15, 2013 von Tina Christensen

    I love JBehave too, I have written the stories/steps/scripts, but I have never set up the framework for it…still having a brain freeze over this information. Any other references regarding the framework for JBehave in Eclipse that you can direct me to would be much appreciated.

  • Hi Andreas,

    The post is much more useful.
    I am using STS, while trying to run the story am getting the below error,

    “Exception in thread “main” java.lang.Error: Unresolved compilation problem:

    at com.bestbuy.fta.ols.JBehaveStoryRunner.main(JBehaveStoryRunner.java:18)”

    Can you please help me out here

  • January 22, 2013 von Rakesh

    Hello Andreas,

    I too found this very useful. Can you give an example where Custom Class data is being passed from Stories to Steps class instead of String and int?

    Thanks,
    Rakesh

  • February 3, 2013 von Giacomo

    Hi
    I am trying to run the second step of the tutorial, but using this code:
    @Override
    public InjectableStepsFactory stepsFactory() {
    return new InstanceStepsFactory(configuration(), new ExampleSteps());
    }

    I see a compile error:
    “The method stepsFactory() of type must override a superclass method”

    It looks like JunitStories class does not have an implementation of the method “stepsFactory(..)”

    How to fix this?

  • April 16, 2013 von Kaustubh

    I just want to know,how calls are made for html report file which user see as report of story execution?
    I want to update html-output.ftl file such a way that when final report gets generated in
    ..\target\jbehave\view\reports.html file, i don’t want columns like Given-story Scenarios, Steps in html output file as I want to delete those permanently ..how i can do that?
    When i see the html-output.ftl file it has very complex code which does not get how the columns are mapped and how to delete the what code…
    …do I need to delete the code in jbehave-core.css file
    as well? Pls suggest
    Also if i made changes in code , how i can make them persistent/permanent so that every time i compile, i don’t see old code…

    • Andreas Ebbert-Karroum

      Hi,

      since you asked the same question on the JBehave users mailing list, the JBehave developers mailing list, and the JBehave SCM mailing list, I believe you get a much larger and more qualified audience than I am.

      Andreas

  • I enjoyed this article very much! My favorite is using de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner as this integrates JBehaves reporting in a very useful way (in fact, this is the way JBehave should have done it). Thank you so much for sharing that class. Perhaps you’ll someday write an article about the planning and thinking in developing that class.

    Cheers,
    ==>Lancer—

  • Although the JUnitReportingRunner runs smoothly in Eclipse, it Freezes during execution in JDeveloper’s JUnit Test runner.

  • July 16, 2013 von Balabharat

    Hi Andreas,

    My SimpleJBehave class is extending junitstories like in your example. I am using Ondemand Sauce Plugin for bamboo, to run jbehave on sauce. I have to print the sauce session id and jbehave scenario name, so that job ids are populated in that plugin.

    ****Please tell me how to get the scenario names.****

    Thanks.
    Balabharat

  • August 7, 2013 von Shishir Dwivedi

    Hi,
    I am running jbehave in eclipse and i am getting storyfilenotfound exception although i am giving correct file address. here is the stack trace please help

    org.jbehave.core.io.StoryResourceNotFound: Story path ‘/jbehaveProject/src/main/java/jbehaveProject/Math.story’ not found by class loader sun.misc.Launcher$AppClassLoader@214c4ac9
    at org.jbehave.core.io.LoadFromClasspath.resourceAsStream(LoadFromClasspath.java:44)
    at org.jbehave.core.io.LoadFromClasspath.loadResourceAsText(LoadFromClasspath.java:29)
    at org.jbehave.core.io.LoadFromClasspath.loadStoryAsText(LoadFromClasspath.java:38)
    at org.jbehave.core.embedder.StoryRunner.storyOfPath(StoryRunner.java:191)
    at de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner.addStories(JUnitReportingRunner.java:192)
    at de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner.buildDescriptionFromStories(JUnitReportingRunner.java:181)
    at de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner.(JUnitReportingRunner.java:51)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.(JUnit4TestReference.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.(JUnit4TestClassReference.java:25)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    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)

    • April 5, 2014 von melvin

      just provide the path from the package name upto the story name

  • hi,
    can any one tell me how to do setup of jbehave in Eclipse?
    so that i will get correct environment ready ?
    thanks

    • April 5, 2014 von melvin

      apart from the jbehave core jar and its dependencies, you will need to install the jbehave eclipse plugin for your version of eclipse.

      also you can use the jbehave-junit monitor runner for this article

  • April 16, 2014 von Blue

    Hi. Great intro. But as a total newbie, could someone please post the minimal Maven pom file needed that’ll take care of all the dependancies (junit/jbehave etc). Thanks :)
    Blue

    • April 17, 2014 von Blue

      I managed to get this compiled and (seemingly) running from the command line (with a lot of pain finding all the libs to include… see my above post about maven pom :) ). But… the tests don’t seen to run. See below output. Any idea what the problem is here? Thanks.

      > java -cp simple;%classpath% org.junit.runner.JUnitCore simple.JTest

      JUnit version 4.11
      Processing system properties {}
      Using controls EmbedderControls[batch=false,skip=false,generateViewAfterStories=
      true,ignoreFailureInStories=false,ignoreFailureInView=false,verboseFailures=fals
      e,verboseFiltering=false,storyTimeoutInSecs=300,failOnStoryTimeout=false,threads
      =1]
      .Running story .\Math.story
      ..Generating reports view to ‘C:\JBehave-Etsy-Selenium-Tutorial\codecentricsimpl
      eexample\target\jbehave’ using formats ‘[stats, junitscenarioreporter]’ and view
      properties ‘{navigator=ftl/jbehave-navigator.ftl, views=ftl/jbehave-views.ftl,
      reports=ftl/jbehave-reports-with-totals.ftl, nonDecorated=ftl/jbehave-report-non
      -decorated.ftl, decorated=ftl/jbehave-report-decorated.ftl, maps=ftl/jbehave-map
      s.ftl}’
      Reports view generated with 0 stories (of which 0 pending) containing 0 scenario
      s (of which 0 pending)
      E
      Time: 0.75
      There was 1 failure:
      1) null
      java.lang.RuntimeException: org.jbehave.core.embedder.Embedder$RunningStoriesFai
      led: Failures in running stories:
      .\Math.story: org.jbehave.core.embedder.StoryManager$StoryExecutionFailed: .\Mat
      h.story
      at de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner.run(JUni
      tReportingRunner.java:81)
      at org.junit.runners.Suite.runChild(Suite.java:127)
      at org.junit.runners.Suite.runChild(Suite.java:26)
      at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
      at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
      at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
      at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
      at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
      at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
      at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
      at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
      at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
      at org.junit.runner.JUnitCore.runMain(JUnitCore.java:96)
      at org.junit.runner.JUnitCore.runMainAndExit(JUnitCore.java:47)
      at org.junit.runner.JUnitCore.main(JUnitCore.java:40)
      Caused by: org.jbehave.core.embedder.Embedder$RunningStoriesFailed: Failures in
      running stories:
      .\Math.story: org.jbehave.core.embedder.StoryManager$StoryExecutionFailed: .\Mat
      h.story
      at org.jbehave.core.embedder.Embedder$ThrowingRunningStoriesFailed.handl
      eFailures(Embedder.java:520)
      at org.jbehave.core.embedder.Embedder.handleFailures(Embedder.java:228)
      at org.jbehave.core.embedder.Embedder.runStoriesAsPaths(Embedder.java:20
      6)
      at de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner.run(JUni
      tReportingRunner.java:79)
      … 14 more

      FAILURES!!!
      Tests run: 2, Failures: 1

  • May 21, 2014 von Thiruvenkadam Thangaraj

    Hi

    I have two stories in my project and i need to pass a story and that story alone should you executed, can you please post the code how it will be possible..

  • August 15, 2014 von Ken phillip

    Hi Andreas

    I have a structure below:
    -Test
    –src/test/java
    —jbehaveReport
    —-simplebehave.story

    Now, at the “SimpleJBehave.java” file, I set the path for my user story following:

    protected List storyPaths() {
    return Arrays.asList(“/src/test/java/jbehaveReport /simplebehave.story”);
    }

    ==> But, after run, I got a error message from Junit: “org.jbehave.core.io.StoryResourceNotFound: Story path ‘/Test/src/test/java/jbehaveReport/simplebehave.story’ not found by class loader sun.misc.Launcher$AppClassLoader@79f71773
    at org.jbehave.core.io.LoadFromClasspath.resourceAsStream(LoadFromClasspath.java:45)
    at org.jbehave.core.io.LoadFromClasspath.loadResourceAsText(LoadFromClasspath.java:30)
    at org.jbehave.core.io.LoadFromClasspath.loadStoryAsText(LoadFromClasspath.java:39)
    at org.jbehave.core.embedder.StoryRunner.storyOfPath(StoryRunner.java:175)
    at de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner.addStories(JUnitReportingRunner.java:192)
    at de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner.buildDescriptionFromStories(JUnitReportingRunner.java:181)
    at de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner.(JUnitReportingRunner.java:51)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.(JUnit4TestReference.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.(JUnit4TestClassReference.java:25)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    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)

    Please help me about that

    Thanks very much.

    • May 20, 2015 von Deepthi

      Hi, Have you figured out the solution to this issue. I have the same issue

  • I am a newbie to Jbehave and im trying to understand its features.

    I got it installed along with eclipse plug in. http://c.gwt-examples.com/home/testing/jbehave-bdd

    got the example downloaded from https://github.com/branflake2267/JBehaveExamples

    Opened in Eclipse. Selected the main story file and run.

    I could see its running, in the console I see the below information :

    Using executor service com.google.common.util.concurrent.MoreExecutors$SameThreadExecutorService@7e668d print

    str=org/gonevertical/test/stories/google_search_test.story

    Processing system properties {} Using controls EmbedderControls[batch=false,skip=false,generateViewAfterStories=true,ignoreFailureInStories=false,ignoreFailureInView=false,verboseFailures=false,verboseFiltering=false,storyTimeoutInSecs=300,threads=1]
    (BeforeStories)

    Nothing happens right after that. Stays as such unless I manually stop it.

    I know this could be very simple but being a beginner, I would be needing help to proceed further.

  • October 21, 2014 von Ramesh

    Hi Andreas,

    This is very useful ..

    I did similar stuff and i could run my automation from past 6 months :)

    Now, the requirement is to externalize the story files from class path … can be an URL …

    I am trying to implement loadFromUrl in my configuration but could not succeed …. Did you try it ? If any one has the implementation to lodad Stories form url … can you please share it

    Thanks,
    Ramesh

  • December 9, 2014 von Rakesh

    I want to continue executing next test step from the scenario even if the previous step fails. Is there any setting for doing it? For Example:
    Then I throw exception (Failed)
    And I do something (Not Performed)
    And I again do validation (Not Performed)

    Can we have a setting where we can execute the steps even if the first step is failed?

    Thanks,
    Rakesh

  • February 26, 2015 von Aat Rutten

    Im trying to introduce BDD in the company I am currently working for. They already have a test framework setup in a continuous integration environment. I have implemented your example in our environment which runs the test during the integration-test phase of maven. The project is setup using the maven-failsafe-plugin so that when an integration-test fails the failure is reported while the rest of the project continues to build successfully. However, when one of the JBehave tests fail the maven build fails as well. Would anybody know how I could configure JBehave tests to fail silently?

    When I make all the JBehave tests pass then the project will build successfully as expected.

    Im using Java 6, jbehave 3.9.2, jbehave-junit-runner 1.1.0.

    Ive tried doing this:
    JUnitReportingRunner.recommandedControls(configuredEmbedder());

    Which does this:
    embedder.embedderControls()
    // don’t throw an exception on generating reports for failing stories
    .doIgnoreFailureInView(true)
    // don’t throw an exception when a story failed
    .doIgnoreFailureInStories(true)
    // .doVerboseFailures(true)
    .useThreads(1);

    Thanks,
    Aat

  • March 24, 2015 von sujit

    Hi Andreas Ebbert-Karroum,

    Have you published the 2nd part of this blog with the details about the configuration and the keypoints.

    Please help if you have any other sources which can help in better understanding of the Configuration Override feature.

    Thanks
    Sujit

  • May 20, 2015 von Deepthi

    hi, I am trying to test our application using Jbehave. I have few test scenarios which are working fine from eclipse. I am trying to create a jar and execute it from the command line. But, i am getting an error saying StoryResourceNotFound. it is not able to locate the story files inside the jar. i am using Jbehave 3.7.5. Could you please help me resolving this. Your help is highly appreciable

    Thanks

  • June 4, 2015 von Igal Epshtein

    I was wonder how doe the GivenStories works along with Examples ?
    I’m executing the next story :

    Scenario: main scenario2
    GivenStories: dummy/Precondition.story#{2}
    Given have string
    When add string
    Then print result

    Examples:
    |first|second|
    |1111|aaaa|
    |2222|bbbbb|
    |3333|rrrr|

    and the Precondition.story is :
    Meta:

    Scenario: precondition scenario
    Given blabla blabla
    When add number
    Then print result

    The thing is , the output I'm getting is :
    (BeforeStories)

    Running story dummy/Main.story

    (dummy/Main.story)
    Scenario: main scenario2
    GivenStories:
    dummy/Precondition.story#{2} {first=3333, second=rrrr}

    (dummy/Precondition.story)
    Scenario: precondition scenario
    Given blabla blabla 3333
    When add number rrrr
    ---->3333rrrr
    Then print result

    Given have string 3333
    When add string rrrr
    ---->3333rrrr
    Then print result

    but if I remove the GivenStories , I’m getting :
    Running story dummy/Main.story


    (dummy/Main.story)
    Scenario: main scenario2
    Examples:
    Given have string
    When add string
    Then print result

    |first|second|
    |1111|aaaa|
    |2222|bbbbb|
    |3333|rrrr|

    Example: {first=1111, second=aaaa}
    Given have string 1111
    When add string aaaa
    ---->1111aaaa
    Then print result

    Example: {first=2222, second=bbbbb}
    Given have string 2222
    When add string bbbbb
    ---->2222bbbbb
    Then print result

    Example: {first=3333, second=rrrr}
    Given have string 3333
    When add string rrrr
    ---->3333rrrr
    Then print result

    I was thinking that the Main.story will be executed as number of rows I have in example table , but it seems that it being executed only once with the specific row I’m providing to GivenStory …

    Where do I wrong ?

  • June 23, 2015 von Deepak

    Thanks, I could user your post to figure out how to get the stories to be displayed (with individual steps) in the JUnit view in eclipse. Very useful library.

Comment

Your email address will not be published. Required fields are marked *