Search code examples
javaspringcucumbercucumber-jvmcucumber-junit

Can I use spring to autowire controller in cucumber test?


I am using Cucumber to automate the testing of services and controllers in my app. In addition, I am using the Cucumber Junit runner @RunWith(Cucumber.class) in the test steps. I need to instantiate my controller and was wondering if I could use Spring to autowire this. The code below shows what I want to do.

public class MvcTestSteps {

//is it possible to do this ????
@Autowired
private UserSkillsController userSkillsController;



/*
 * Opens the target browser and page objects
 */
@Before
public void setup() {
    //insted of doing it like this???
    userSkillsController = (UserSkillsController) appContext.getBean("userSkillsController");
    skillEntryDetails = new SkillEntryRecord();

}

Solution

  • I used cucumber-jvm to autowire Spring into Cucumber.

    <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>1.1.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-spring</artifactId>
            <version>1.1.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.1.5</version>
            <scope>test</scope>
        </dependency>
    

    And import applicationContext.xml into Cucumber.xml

    <import resource="/applicationContext.xml" />   // refer to appContext in test package
    <context:component-scan base-package="com.me.pos.**.it" />   // scan package IT and StepDefs class
    

    In CucumberIT.java call @RunWith(Cucumber.class) and add the CucumberOptions.

    @RunWith(Cucumber.class)
    @CucumberOptions(
        format = "pretty",
        tags = {"~@Ignore"},
        features = "src/test/resources/com/me/pos/service/it/"  //refer to Feature file
    )
    public class CucumberIT {  }
    

    In CucumberStepDefs.java you can @Autowired Spring

    @ContextConfiguration("classpath:cucumber.xml")
    public class CucumberStepDefs {
    
        @Autowired
        SpringDAO dao;
    
        @Autowired
        SpringService service;
    }