简体   繁体   中英

How to @Autowire a REST service class (Spring boot) in a Cucumber step implementation?

Like the title says, I want to test a Scenario in Cucumber where I add a new DTO to the database using a method of my service class. The issue is that I can't use @Autowire, and don't know how to enable it. I've attempted several solutions for similar questions (Like this one) , but I don't know where I'm going wrong. For reference, I'm doing this in Intellij and and this is what my structure looks like:

项目结构

This is my Cucumber start class:

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/unit/resources/features")
public class RunCucumberUnitTest {

}

And this is the BaseStep class that all steps are going to inherit:

@ContextConfiguration(classes = {BasicLoginTestApplication.class},
                      initializers = ConfigFileApplicationContextInitializer.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class BaseStep {
}

In my step implementation, I attempt this:

public class UserServiceTestStepImplementation extends BaseStep{

    @Autowired
    UserService userService;

But I still get a null pointer exception for the userService. I'd really like some ideas on what I could do.

EDIT: I tried to add a dummy method to the BaseStep class to make Cucumber recognize it as glue. I think that happened, but then I got an exception saying I can't extend step implementation classes or hooks. I removed the extend from the StepImplementation class and just put the annotations there. Still get null pointer exception. This is the step impl. now:

@ContextConfiguration(classes = {BasicLoginTestApplication.class},
    initializers = ConfigFileApplicationContextInitializer.class)
@SpringBootTest(webEnvironment =   SpringBootTest.WebEnvironment.DEFINED_PORT)
public class UserServiceTestStepImplementation /*extends BaseStep*/{

    @Autowired
    UserService userService;

    @Before
    public void springContext() {

    }

You might have to add to your BaseStep class this code

@Before
public void setup_cucumber_spring_context(){
    // Dummy method so cucumber will recognize this class as glue
    // and use its context configuration.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM