Writing Steps in Groovy

Groovy is a very powerful dynamic scripting language that compiles directly to the JVM.

JBehave supports writing Steps classes directly in Groovy, using the GroovyStepsFactory and providing the list of Groovy scripts as classpath resources:

@RunWith(JUnitReportingRunner.class)
public class GroovyStories extends JUnitStories {
 
    @Override
    public Configuration configuration() {
        return new MostUsefulConfiguration().useStoryReporterBuilder(new StoryReporterBuilder().withFormats(HTML));
    }
 
    @Override
    protected List<String> storyPaths() {
        return new StoryFinder()
                .findPaths(codeLocationFromClass(this.getClass()).getFile(), asList("**/*.story"), null);
    }
 
    @Override
    public InjectableStepsFactory stepsFactory() {
        GroovyResourceFinder resourceFinder = new GroovyResourceFinder(codeLocationFromPath("src/main/groovy"), "**/*.story", "");
        return new GroovyStepsFactory(configuration(), new GroovyContext(resourceFinder));
    }
 
}

It is also possible to use the Groovy compiler to directly compile Java class files. If this is done, the setup is simpler. The JBehave Tutorial shows a Maven POM file and a runtime configuration that compiles Groovy into Java bytecode before use.

The Groovy script needs to include annotated methods, just as you would in Java:

import org.jbehave.core.annotations.Given
import org.jbehave.core.annotations.Then
import org.jbehave.core.annotations.When
 
import static junit.framework.Assert.assertNotNull;
 
class ExampleGroovySteps {
 
  @Given("a date of \$date")
  def date(Date date) {
    assertNotNull(date);
  }
 
  @When("\$days days pass")
  def daysPass(int days) {
    assertNotNull(days);
  }
 
  @Then("the date is \$date")
  def theDate(Date date) {
      assertNotNull(date);
  }
 
}

Using Annotations

@RunWith(GroovyAnnotatedEmbedderRunner.class)
@Configure()
@UsingEmbedder();
@UsingGroovy(classLoader = MyGroovyClassLoader.class, resourceFinder = MyGroovyResourceFinder.class)
public class AnnotatedEmbedderUsingGroovy extends InjectableEmbedder {
 
    @Test
    public void run() {
        injectedEmbedder().runStoriesAsPaths(storyPaths());
    }
 
    protected List<String> storyPaths() {
        return new StoryFinder()
                .findPaths(codeLocationFromClass(this.getClass()).getFile(), asList("**/*.story"), null);
    }
     
}