I am writing a new app and trying to do BDD using cucumber and Spring Boot 1.4. Working code is as shown below:
@SpringBootApplication
public class Application {
@Bean
MyService myService() {
return new MyService();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
public class MyService {}
Test code is as shown below:
@RunWith(Cucumber.class)
public class RunFeatures {}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class, loader = SpringApplicationContextLoader.class)
public class MyStepDef {
@Autowired
MyService myService;
@Given("^Some initial condition$")
public void appIsStarted() throws Throwable {
if (service == null) throw new Exception("Dependency not injected!");
System.out.println("App started");
}
@Then("^Nothing happens$")
public void thereShouldBeNoException() throws Throwable {
System.out.println("Test passed");
}
}
Feature file is as shown below:
Feature: Test Cucumber with spring
Scenario: First Scenario
Given Some initial condition
Then Nothing happens
When I run the above as is, all works well and dependency (MyService) is injected into MyStepDef with no issues.
If I replace this code:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class, loader = SpringApplicationContextLoader.class)
With the code below (New way to handle it in Spring Boot 1.4):
@RunWith(SpringRunner.class)
@SpringBootTest
Then the dependency (MyService) never gets injected. Am I missing something perhaps?
Thanks in advance for your help!!!
I had the same problem. The comment from above directed me to the solution
The problematic code in cucumber-spring seems to be this github.com/cucumber/cucumber-jvm/blob/master/spring/src/main/…
After adding the annotation @ContextConfiguration
the tests are working as expected.
So what i've got is the following...
@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"json:target/cucumber.json", "pretty"}, features = "src/test/features")
public class CucumberTest {
}
@ContextConfiguration
@SpringBootTest
public abstract class StepDefs {
}
public class MyStepDefs extends StepDefs {
@Inject
Service service;
@Inject
Repository repository;
[...]
}
I hope this helps you further