Cucumber with Spring Boot 1.4: Dependencies not injected when using @SpringBootTest and @RunWith(SpringRunner.class)

后端 未结 5 1610
情深已故
情深已故 2021-02-07 16:43

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 {         


        
5条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 16:57

    I got it working with Spring Boot 1.5.x and 2.0 and then wrote a blog post to try to clarify this since it's tricky.

    First, even if it's obvious, you need to have the right dependencies included in your project (being cucumber-spring the important one here). For example, with Maven:

    
        io.cucumber
        cucumber-java
        2.3.1
        test
    
    
        io.cucumber
        cucumber-junit
        2.3.1
        test
    
    
        io.cucumber
        cucumber-spring
        2.3.1
        test
    
    

    Now, the important part to make it work, summarized:

    • The entry point to your test should be a class annotated with @RunWith(Cucumber.class.
    • This class will use the steps definitions, which are normally in a separated class with annotated methods (@Given, @When, @Then, etc.).
    • The trick is that this class should extend a base class annotated with @SpringBootTest, @RunWith(SpringRunner.class) and any other configuration you need to run your test with Spring Boot. For instance, if you're implementing an integration test without mocking other layers, you should add the webEnvironment configuration and set it to RANDOM_PORT or DEFINED_PORT.

    See the diagram and the code skeleton below.

    The entry point:

    @RunWith(Cucumber.class)
    @CucumberOptions(features = "src/test/resources/features/bag.feature", plugin = {"pretty", "html:target/cucumber"})
    public class BagCucumberIntegrationTest {
    }
    

    The Spring Boot base test class:

    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public abstract class SpringBootBaseIntegrationTest {
    }
    

    The step definitions class:

    @Ignore
    public class BagCucumberStepDefinitions extends SpringBootBaseIntegrationTest {
      // @Given, @When, @Then annotated methods
    }
    

    This is what you need to make DI work. For the full code example, just check my blog post or the code in GitHub.

提交回复
热议问题