Reputation: 399
Im am using mockito together with cucumber where mocks and stepdefinitions are all defined together in one class which is working fine. I now wish to refactor my code into smaller step definitions classes and rather access my mocks via static helpers from each stepDefinition class. My problem is that im unable to initialze my mocks when they are separate from my stepDefinitions classes.
Modules:
cucumber-junit 4.8.0
cucumber-java 4.8.0
mockito-core 3.3.3
I wish to do something like this:
@RunWith(Cucumber.class)
@CucumberOptions(
plugin = {"pretty", "html:target/cucumber"},
features = {"src/test/resources/features"},
glue = {"bdd.steps"},
monochrome = true)
public class RunCucumberTest {
}
public class MockDataHelper{
@Mock private BookService bookService;
@Getter
private static Library library;
@Before
public void before() {
MockitoAnnotations.initMocks(this);
library = new Library(bookService);
}
package bdd.steps;
public class StepsA {
@Given("..") {
...
@When("..") {
MockDataWrapper.getLibrary().rentBook(..);
}
package bdd.steps;
public class StepsB {
@Given("..")
...
}
I could achieve what I want with a factory method, but was hoping for a more elegant solution..
public Library getLibrary(){
if(library == null){
library = new Library(mock(bookService.class));
}
return library;
}
Any help is much appreciated
Upvotes: 1
Views: 1958
Reputation: 12039
Cucumber supports various dependency injection containers. If you add cucumber-pico
as a dependency all you have to do is declare a constructor. As you're using Lombok this is a matter of adding @RequiredArgConstructor
.
@RequiredArgConstructor
public class StepsA {
private final MockDataWrapper wrapper
@When("..") {
wrapper.getLibrary().rentBook(..);
}
}
Do make sure that MockDataHelper
is on the glue path. Otherwise the @Before
hook won't be triggered.
Upvotes: 1