I have the following feature file: MacroValidation.feature
#macroFilter
Feature: Separating out errors and warnings
Scenario: No errors or warnings when separating out error list
Given I have 0 macros
When I filter out errors and warnings for Macros
Then I need to have 0 errors
And I need to have 0 warnings
My definition files.
package com.test.definition;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import cucumber.runtime.java.StepDefAnnotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.spy;
#StepDefAnnotation
public class MacroValidationStepDefinitions {
private final MacroService macroService = spy(new MacroService());
private final LLRBusList busList = mock(LLRBusList.class);
private final List<String> errorList = new ArrayList<String>();
private final List<String> warningList = new ArrayList<String>();
#Before({"#macroFilter"})
public void setUp() {
errorList.addAll(Arrays.asList("error 1, error2, error 3"));
warningList.addAll(Arrays.asList("warning 1, warning 2, warning 3"));
}
#After({"#macroFilter"})
public void tearDown() {
errorList.clear();
warningList.clear();
}
#Given("^I have (\\d+) macros$")
public void i_have_macros(int input) {
doReturn(input).when(busList).size();
}
#When("^I filtered out errors and warnings for Macros$")
public void i_filtered_out_errors_and_warnings_for_Macros() {
macroService.separateErrorsAndWarning(busList, errorList, warningList);
}
#Then("^I need to have (\\d+) errors$")
public void i_need_to_have_errors(int numOfError) {
if (numOfError == 0) {
assertTrue(errorList.isEmpty());
} else {
assertEquals(errorList.size(), numOfError);
}
}
#Then("^I need to have (\\d+) warnings$")
public void i_need_to_have_warnings(int numOfWarnings) {
if (numOfWarnings == 0) {
assertTrue(warningList.isEmpty());
} else {
assertEquals(warningList.size(), numOfWarnings);
}
}
}
My unit test class.
#CucumberOptions(features = {"classpath:testfiles/MacroValidation.feature"},
glue = {"com.macro.definition"},
dryRun = false,
monochrome = true,
tags = "#macroFilter"
)
#RunWith(Cucumber.class)
public class PageMacroValidationTest {
}
When I execute the test, I get file definition not implemented warnings in the log.
Example log:
You can implement missing steps with the snippets below:
#Given("^I have (\\d+) macros$")
public void i_have_macros(int arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#When("^I filter out errors and warnings for Macros$")
public void i_filter_out_errors_and_warnings_for_Macros() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#Then("^I need to have (\\d+) errors$")
public void i_need_to_have_errors(int arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#Then("^I need to have (\\d+) warnings$")
public void i_need_to_have_warnings(int arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
I don't think file name should matter right?
It looks like Cucumber isn't finding your step defintion class. In your unit test class you say:
glue = {"com.macro.definition"}
However the step definition classes are in com.test.definition
Try changing that line to:
glue = {"com.test.definition"}
You may have to rebuild your project to pick up the change.
Also, Cucumber is sensitive to white space. If you try to make your runner or feature file pretty after having captured the snippets, you will get this problem.
Here's an example that drove me nuts for several hours while creating my first BDD. I had created the feature file and a skeleton runner which I ran and and captured the snippets. Then I prettified the feature file, and when I ran the runner got the errors.
Of course everything looked fine to my human brain, so the next few hours were spent in fruitless research here, and checking versions and bug lists. Finally I decided to compare the first two lines of the snippet to see what was different:
// #Then("^the test result is = \"([^\"]*)\"$")
// public void theTestResultIs(String ruleResult) throws Throwable {
#Then("^the test result is = \"([^\"]*)\"$")
public void theTestResultIs(String arg1) throws Throwable {
Doh!
Try to use all dependencies in POM.xml with io.cucumber group id which is the latest jars instead of info.cukes. After removing jars update the project with new imports and run the project.
Remember you have to replace all dependencies of info.cukes with io.cucumber
Related
I have this weird case where I want to test "some" functionality without touching the other... it's very hard for me to choose a proper description and I hope that the code I will present below is pretty much self descriptive.
Suppose I have a class that keeps some strategies:
class TypeStrategy {
private static final CreateConsumer CREATE_CONSUMER = new CreateConsumer();
private static final ModifyConsumer MODIFY_CONSUMER = new ModifyConsumer();
private static final Map<Type, Consumer<ConsumerContext>> MAP = Map.of(
Type.CREATE, CREATE_CONSUMER,
Type.MODIFY, MODIFY_CONSUMER
);
public static void consume(Type type, ConsumerContext context) {
Optional.ofNullable(MAP.get(nodeActionType))
.orElseThrow(strategyMissing(type))
.accept(context);
}
}
The idea is very easy - there are some strategies that are registered for a certain Type; method consume will simply try to find a proper registered type and invoke consume on it with the supplied ConsumerContext.
And now the problem: I very much want to test that all the strategies I care about are registered and I can invoke accept on them - that is literally all I want to test.
Usually, I would use #SuppressStaticInitializationFor on the TypeStrategy and using WhiteBox::setInternalState would just put whatever I need for CREATE_CONSUMER and MODIFY_CONSUMER; but in this case I can't, because the MAP will be skipped also and I really don't want that, all I care about is those two strategies - I need the MAP to stay as it is.
Besides some nasty refactoring, that does get me where I sort of want to be, I am out of ideas how can I achieve this. In the best case scenario I hoped that #SuppressStaticInitializationFor would support some "partial" skipping, where you could specify some filter on what exactly you want skipped , but that is not an option, really.
I could also test "everything" else on the chain of calls - that is test everything that accept is supposed to do, but that adds close to 70 lines of mocking in this test and it becomes a nightmare to understand that it really wants to test a very small piece.
From your description it seems black-box testing is not an option, so perhaps we can rely on some white-box tests by mocking the constructors of your consumers, and verifying their interactions.
Below you can find a complete example extrapolated from your initial sample, including a possible option for .orElseThrow(strategyMissing(type)).
One important note/disclaimer: since we're leaving TypeStrategy intact, this means the static initialization block for the map will be executed. Thus, we need to pay special attention to the consumer mock instances. We need to make sure that the same mock instances added in the map during the initial mocking phase, are available in all the tests, otherwise the verification will fail. So instead of creating mocks for each test, we will create them once for all tests. While this is not recommended in unit testing (tests should be isolated and independent), I believe in this special case it's a decent trade-off one can live with.
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.AbstractMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.whenNew;
// enable powermock magic
#RunWith(PowerMockRunner.class)
#PrepareForTest({MockitoTest.TypeStrategy.class})
public class MockitoTest {
private static CreateConsumer createConsumerMock;
private static ModifyConsumer modifyConsumerMock;
// static initializer in TypeStrategy => mock everything once in the beginning to avoid having new mocks for each test (otherwise "verify" will fail)
#BeforeClass
public static void setup() throws Exception {
// mock the constructors to return mocks which we can later check for interactions
createConsumerMock = mock(CreateConsumer.class);
modifyConsumerMock = mock(ModifyConsumer.class);
whenNew(CreateConsumer.class).withAnyArguments().thenReturn(createConsumerMock);
whenNew(ModifyConsumer.class).withAnyArguments().thenReturn(modifyConsumerMock);
}
#Test
public void shouldDelegateToCreateConsumer() {
checkSpecificInteraction(Type.CREATE, createConsumerMock);
}
#Test
public void shouldDelegateToModifyConsumer() {
checkSpecificInteraction(Type.MODIFY, modifyConsumerMock);
}
private void checkSpecificInteraction(Type type, Consumer<ConsumerContext> consumer) {
ConsumerContext expectedContext = new ConsumerContext();
// invoke the object under test
TypeStrategy.consume(type, expectedContext);
// check interactions
verify(consumer).accept(expectedContext);
}
#Test
public void shouldThrowExceptionForUnsupportedConsumer() {
ConsumerContext expectedContext = new ConsumerContext();
// unsupported type mock
Type unsupportedType = PowerMockito.mock(Type.class);
when(unsupportedType.toString()).thenReturn("Unexpected");
// powermock does not play well with "#Rule ExpectedException", use plain old try-catch
try {
// invoke the object under test
TypeStrategy.consume(unsupportedType, expectedContext);
// if no exception was thrown to this point, the test is failed
fail("Should have thrown exception for unsupported consumers");
} catch (Exception e) {
assertThat(e.getMessage(), is("Type [" + unsupportedType + "] not supported"));
}
}
/* production classes below */
public static class TypeStrategy {
private static final CreateConsumer CREATE_CONSUMER = new CreateConsumer();
private static final ModifyConsumer MODIFY_CONSUMER = new ModifyConsumer();
private static final Map<Type, Consumer<ConsumerContext>> MAP = Stream.of(
new AbstractMap.SimpleEntry<>(Type.CREATE, CREATE_CONSUMER),
new AbstractMap.SimpleEntry<>(Type.MODIFY, MODIFY_CONSUMER)
).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
public static void consume(Type type, ConsumerContext context) {
Optional.ofNullable(MAP.get(type))
.orElseThrow(strategyMissing(type))
.accept(context);
}
private static Supplier<IllegalArgumentException> strategyMissing(Type type) {
return () -> new IllegalArgumentException("Type [" + type + "] not supported");
}
}
public static class CreateConsumer implements Consumer<ConsumerContext> {
#Override
public void accept(ConsumerContext consumerContext) {
throw new UnsupportedOperationException("Not implemented");
}
}
public static class ModifyConsumer implements Consumer<ConsumerContext> {
#Override
public void accept(ConsumerContext consumerContext) {
throw new UnsupportedOperationException("Not implemented");
}
}
public enum Type {
MODIFY, CREATE
}
public static class ConsumerContext {
}
}
I'm learning Arquillian right now I wonder how to create page that has a placeholder inside the path. For example:
#Location("/posts/{id}")
public class BlogPostPage {
public String getContent() {
// ...
}
}
or
#Location("/posts/{name}")
#Location("/specific-page?requiredParam={value}")
I have looking for an answer on graphine and arquillian reference guides without success. I used library from other language that have support for page-objects, but it has build-in support for placeholders.
AFAIK there is nothing like this implemented in Graphene.
To be honest, I'm not sure how this should behave - how would you pass the values...?
Apart from that, I think that it could be also limited by Java annotation abilities https://stackoverflow.com/a/10636320/6835063
This is not possible currently in Graphene. I've created ARQGRA-500.
It's possible to extend Graphene to add dynamic parameters now. Here's how. (Arquillian 1.1.10.Final, Graphene 2.1.0.Final.)
Create an interface.
import java.util.Map;
public interface LocationParameterProvider {
Map<String, String> provideLocationParameters();
}
Create a custom LocationDecider to replace the corresponding Graphene's one. I replace the HTTP one. This Decider will add location parameters to the URI, if it sees that the test object implements our interface.
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.graphene.location.decider.HTTPLocationDecider;
import org.jboss.arquillian.graphene.spi.location.Scheme;
import org.jboss.arquillian.test.spi.context.TestContext;
public class HTTPParameterizedLocationDecider extends HTTPLocationDecider {
#Inject
private Instance<TestContext> testContext;
#Override
public Scheme canDecide() {
return new Scheme.HTTP();
}
#Override
public String decide(String location) {
String uri = super.decide(location);
// not sure, how reliable this method of getting the current test object is
// if it breaks, there is always a possibility of observing
// org.jboss.arquillian.test.spi.event.suite.TestLifecycleEvent's (or rather its
// descendants) and storing the test object in a ThreadLocal
Object testObject = testContext.get().getActiveId();
if (testObject instanceof LocationParameterProvider) {
Map<String, String> locationParameters =
((LocationParameterProvider) testObject).provideLocationParameters();
StringBuilder uriParams = new StringBuilder(64);
boolean first = true;
for (Entry<String, String> param : locationParameters.entrySet()) {
uriParams.append(first ? '?' : '&');
first = false;
try {
uriParams.append(URLEncoder.encode(param.getKey(), "UTF-8"));
uriParams.append('=');
uriParams.append(URLEncoder.encode(param.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
uri += uriParams.toString();
}
return uri;
}
}
Our LocationDecider must be registered to override the Graphene's one.
import org.jboss.arquillian.core.spi.LoadableExtension;
import org.jboss.arquillian.graphene.location.decider.HTTPLocationDecider;
import org.jboss.arquillian.graphene.spi.location.LocationDecider;
public class MyArquillianExtension implements LoadableExtension {
#Override
public void register(ExtensionBuilder builder) {
builder.override(LocationDecider.class, HTTPLocationDecider.class,
HTTPParameterizedLocationDecider.class);
}
}
MyArquillianExtension should be registered via SPI, so create a necessary file in your test resources, e.g. for me the file path is src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension. The file must contain a fully qualified class name of MyArquillianExtension.
And that's it. Now you can provide location parameters in a test.
import java.util.HashMap;
import java.util.Map;
import org.jboss.arquillian.graphene.page.InitialPage;
import org.jboss.arquillian.graphene.page.Location;
import org.junit.Test;
public class TestyTest implements LocationParameterProvider {
#Override
public Map<String, String> provideLocationParameters() {
Map<String, String> params = new HashMap<>();
params.put("mykey", "myvalue");
return params;
}
#Test
public void test(#InitialPage TestPage page) {
}
#Location("MyTestView.xhtml")
public static class TestPage {
}
}
I've focused on parameters specifically, but hopefully this paves the way for other dynamic path manipulations.
Of course this doesn't fix the Graphene.goTo API. This means before using goTo you have to provide parameters via this roundabout provideLocationParameters way. It's weird. You can make your own alternative API, goTo that accepts parameters, and modify your LocationDecider to support other ParameterProviders.
I want to ask that is there a way to do Pretty formatting in xtext automatically without (ctrl+shift+f) or turning it on from preference menu. What I actually want is whenever a user completes writing the code it is automatically pretty formatted (or on runtime) without (ctrl+shift+f).
There is a way for doing that which is called "AutoEdit". It's not exactly when the user completes writing but it's with every token. That's at least what I have done. You can for sure change that. I will give you an example that I implemented myself for my project. It basically capitalizes everykeyword as the user types (triggered by spaces and endlines).
It is a UI thing. So, In your UI project:
in MyDslUiModule.java you need to attach your AutoEdit custom made class do that like this:
public Class<? extends DefaultAutoEditStrategyProvider> bindDefaultAutoEditStrategyProvider()
{
return MyDslAutoEditStrategyProvider.class;
}
Our class will be called MyDslAutoEditStrategyProvider so, go ahead and create it in a MyDslAutoEditStrategyProvider.java file. Mine had this to do what i explained in the introduction:
import java.util.Set;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.xtext.GrammarUtil;
import org.eclipse.xtext.IGrammarAccess;
import org.eclipse.xtext.ui.editor.autoedit.DefaultAutoEditStrategyProvider;
import org.eclipse.xtext.ui.editor.model.XtextDocument;
import com.google.inject.Inject;
import com.google.inject.Provider;
public class MyDslAutoEditStrategyProvider extends DefaultAutoEditStrategyProvider {
#Inject
Provider<IGrammarAccess> iGrammar;
private Set<String> KWDS;
#Override
protected void configure(IEditStrategyAcceptor acceptor) {
KWDS = GrammarUtil.getAllKeywords(iGrammar.get().getGrammar());
IAutoEditStrategy strategy = new IAutoEditStrategy()
{
#Override
public void customizeDocumentCommand(IDocument document, DocumentCommand command)
{
if ( command.text.length() == 0 || command.text.charAt(0) > ' ') return;
IRegion reg = ((XtextDocument) document).getLastDamage();
try {
String token = document.get(reg.getOffset(), reg.getLength());
String possibleKWD = token.toLowerCase();
if ( token.equals(possibleKWD.toUpperCase()) || !KWDS.contains(possibleKWD) ) return;
document.replace(reg.getOffset(), reg.getLength(), possibleKWD.toUpperCase());
}
catch (Exception e)
{
System.out.println("AutoEdit error.\n" + e.getMessage());
}
}
};
acceptor.accept(strategy, IDocument.DEFAULT_CONTENT_TYPE);
super.configure(acceptor);
}
}
I assume you saying "user completes writing" can be as "user saves file". If so here is how to trigger the formatter on save:
in MyDslUiModule.java:
public Class<? extends XtextDocumentProvider> bindXtextDocumentProvider()
{
return MyDslDocumentProvider.class;
}
Create the MyDslDocumentProvider class:
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.xtext.ui.editor.model.XtextDocumentProvider;
public class MyDslDocumentProvider extends XtextDocumentProvider
{
#Override
protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
throws CoreException {
IHandlerService service = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class);
try {
service.executeCommand("org.eclipse.xtext.ui.FormatAction", null);
} catch (Exception e)
{
e.printStackTrace();
}
super.doSaveDocument(monitor, element, document, overwrite);
}
}
I'm designing an Eclipse plugin designed around a new perspective with an editor that stores code/comment snippets upon highlighting them. The parts to it include: the perspective, the editor, and a mouselistener.
I have the perspective made and can open it. I have the editor class code constructed, however, on programmatically opening the editor via IWorkbenchPart.openEditor() my custom editor does not seem to be initialized in any way. Only the default Eclipse editor appears. I can tell because my custom mouse events do not fire.
I used the vogella tutorial as a reference.
Why is my editor's init() method not being called upon being opened? I can tell it is not since the print statement in both init() and createPartControl() are not executed.
In googling this problem, I found a number of hits but they all revolved around error messages encountered (can't find editor, can't find file, ...). I am getting no error messages, just unexpected behaviour. So those articles were useless.
(I would ideally like a TextViewer instead, since I don't want them editing the contents in this mode anyway, but I decided to start here.)
Code below.
Perspective:
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
public class PluginPerspective implements IPerspectiveFactory {
#Override
public void createInitialLayout(IPageLayout layout) {
layout.setEditorAreaVisible(true);
layout.setFixed(true);
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorInput iei = page.getActiveEditor().getEditorInput();
try
{
// Open Editor code nabbed from Vogella tutorial.
// He creates an action to do so - I force it to happen when the
// perspective is created.
// I get the name of the current open file as expected.
System.out.println(iei.getName());
page.openEditor(iei, myplugin.PluginEditor.ID, true);
// This message prints, as expected.
System.out.println("open!");
} catch (PartInitException e) {
throw new RuntimeException(e);
}
}
}
Editor: (Removed the other basic editor stubs (isDirty, doSave) since they are not pertinent)
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.TextViewer;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.ui.texteditor.ITextEditor;
public class PluginEditor extends EditorPart implements MouseListener {
public static final String ID = "myplugin.plugineditor";
#Override
public void init(IEditorSite site, IEditorInput input)
throws PartInitException {
// TODO Auto-generated method stub
System.out.println("editor init!");
setSite(site);
setInput(input);
}
#Override
public void createPartControl(Composite parent) {
// TODO Auto-generated method stub
System.out.println("editor partcontrol!");
//TextViewer tv = new TextViewer(parent, 0);
//tv.setDocument(getCurrentDocument());
}
#Override
public void mouseDoubleClick(MouseEvent e) {
// TODO Auto-generated method stub
// nothing?
}
#Override
public void mouseDown(MouseEvent e) {
// TODO Auto-generated method stub
// grab start location?
System.out.println("down!");
}
#Override
public void mouseUp(MouseEvent e) {
// TODO Auto-generated method stub
// do stuff!
System.out.println("up!");
}
// to be used for grabbing highlight-selection grabbing later
public IDocument getCurrentDocument() {
final IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.getActiveEditor();
if (!(editor instanceof ITextEditor)) return null;
ITextEditor ite = (ITextEditor)editor;
IDocument doc = ite.getDocumentProvider().getDocument(ite.getEditorInput());
return doc;
//return doc.get();
}
}
Have you registered your editor within your plugin.xml?
<extension
point="org.eclipse.ui.editors">
<editor
default="false"
id="myplugin.plugineditor"
name="name">
</editor>
</extension>
Also, you may want to implement IEditorInput to have specific input for your editor.
I'm trying to set up JBehave for testing web services.
Template story is running well, but I can see in JUnit Panel only Acceptance suite class execution result. What I want is to see execution result for each story in suite and for each step in story like it is shown in simple JUnit tests or in Thucydides framework.
Here is my acceptance suite class: so maybe I Haven't configured something, or either I have to notate my step methods some other way, but I didn't find an answer yet.
package ***.qa_webservices_testing.jbehave;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.jbehave.core.Embeddable;
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.parsers.RegexPrefixCapturingPatternParser;
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.jbehave.core.steps.ParameterConverters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ***.qa_webservices_testing.jbehave.steps.actions.TestAction;
/**
* suite class.
*/
public class AcceptanceTestSuite extends JUnitStories {
private static final String CTC_STORIES_PATTERN = "ctc.stories";
private static final String STORY_BASE = "src/test/resources";
private static final String DEFAULT_STORY_NAME = "stories/**/*.story";
private static final Logger LOGGER = LoggerFactory.getLogger(AcceptanceTestSuite.class);
private final CrossReference xref = new CrossReference();
public AcceptanceTestSuite() {
configuredEmbedder()
.embedderControls()
.doGenerateViewAfterStories(true)
.doIgnoreFailureInStories(false)
.doIgnoreFailureInView(true)
.doVerboseFailures(true)
.useThreads(2)
.useStoryTimeoutInSecs(60);
}
#Override
public Configuration configuration() {
Class<? extends Embeddable> embeddableClass = this.getClass();
Properties viewResources = new Properties();
viewResources.put("decorateNonHtml", "true");
viewResources.put("reports", "ftl/jbehave-reports-with-totals.ftl");
// Start from default ParameterConverters instance
ParameterConverters parameterConverters = new ParameterConverters();
return new MostUsefulConfiguration()
.useStoryLoader(new LoadFromClasspath(embeddableClass))
.useStoryReporterBuilder(new StoryReporterBuilder()
.withCodeLocation(CodeLocations.codeLocationFromClass(embeddableClass))
.withDefaultFormats()
.withViewResources(viewResources)
.withFormats(Format.CONSOLE, Format.TXT, Format.HTML_TEMPLATE, Format.XML_TEMPLATE)
.withFailureTrace(true)
.withFailureTraceCompression(false)
.withMultiThreading(false)
.withCrossReference(xref))
.useParameterConverters(parameterConverters)
// use '%' instead of '$' to identify parameters
.useStepPatternParser(new RegexPrefixCapturingPatternParser(
"%"))
.useStepMonitor(xref.getStepMonitor());
}
#Override
protected List<String> storyPaths() {
String storiesPattern = System.getProperty(CTC_STORIES_PATTERN);
if (storiesPattern == null) {
storiesPattern = DEFAULT_STORY_NAME;
} else {
storiesPattern = "**/" + storiesPattern;
}
LOGGER.info("will search stories by pattern {}", storiesPattern);
List<String> result = new StoryFinder().findPaths(STORY_BASE, Arrays.asList(storiesPattern), Arrays.asList(""));
for (String item : result) {
LOGGER.info("story to be used: {}", item);
}
return result;
}
#Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new TestAction());
}
}
my test methods look like:
Customer customer = new cutomer();
#Given ("I have Access to Server")
public void givenIHaveAccesToServer() {
customer.haveAccesToServer();
}
So they are notated only by JBehave notations.
The result returned in Junit panel is only like here (I yet have no rights to post images):
You should try this open source library:
https://github.com/codecentric/jbehave-junit-runner
It does exactly what you ask for :)
Yes, the codecentric runner works very nicely.
https://github.com/codecentric/jbehave-junit-runner