Search code examples
javaspringspring-bootcucumbercucumber-junit

@Autowire not working for my spring-cucumber acceptance tests


I have just started working with Cucumber and I am not able to configure spring with it(for autowire getting error -> org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type (MyClass) available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)})

I have created separate module for Acceptance test outside Service of my project Below is my project structure - Structure

CucumberIntegrationTest.java ->

@Cucumber
@CucumberOptions(features = "classpath:feature/" ,
                 glue = {"com.asite.iotgateway.cucumberspringboot.cucumberGlue" ,
                         "com.asite.iotgateway.cucumberspringboot.service"})
@SpringBootConfiguration
public class CucumberIntegrationTest {

}

SpringIntegrationTest.java ->

@SpringBootTest
@CucumberContextConfiguration
public class SpringIntegrationTest {

}

Please suggest if I am doing this right, I am using @Autowire in my PreferenceStepDefinition.java file. Is it compulsory to have Application.java file with @SpringBootApplication to use spring functionality with acceptance tests as well?


Solution

  • There are a few problemens.

    1.

    Your CucumberIntegrationTest is mixing JUnit 4 and JUnit 5 annotations and will never work in the way you assume it does.

    You can either use cucumber-junit with JUnit Vintage and JUnit 5 or you can use the cucumber-junit-platform-engine and the JUnit 5 Suite with with JUnit 5.

    2.

    The SpringIntegrationTest is the class used by Cucumber to tell Spring how to build the application context. If you were using JUnit this would be the class you would put your tests methods in.

    So if you can not get this to work as a JUnit test, it also won't work for Cucumber.

    And yes, generally speaking when using @SpringBootTest you also need @SpringBootApplication. But you don't have to use @SpringBootTest to build an application context. It is however much less work.

    3.

    You didn't provide enough details to reproduce your problem. Please have a look at How to create a Minimal, Reproducible Example.