I am trying to move common Cucumber step definitions from our spring applications into its own library. This way I can reuse the same functions across multiple services.
However, to run some of the step definitions I need access to Application context and MockMvc. Is there a way to autowire the a bean from any spring application into my library?
I've tried the following in library
@SpringBootTest(classes = StepDefinitonConfig.class)
@AutoConfigureMockMvc
public class StepDefinitonConfig {
@Autowired
protected MockMvc mockMvc;
@Autowired
protected ApplicationContext applicationContext;
}
mockMvc.perform(post(url/here)...
MockWebServiceClient mockWs = MockWebServiceClient.createClient(applicationContext);
And this in the spring application
@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/bdd",
glue = {"com.my.library.etc"})
I assume I'm missing a key principle of how the spring scans the classpath, but cant see it!
If you are using cucumber-spring
you can autowire any bean, including the application context into your step definitions. It does not matter where you step definitions are, as long as they are on the glue path.
package com.example.lib;
public class MyStepDefinitions {
@Autowired
private MyService myService;
@Given("feed back is requested from my service")
public void feed_back_is_requested(){
myService.requestFeedBack();
}
}
So if some of your step definitions are in the com.example.lib
package and some in the com.example.app
package you'd include both by using:
package com.example;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(glue = {"com.example.app", "com.example.lib"})
public class RunCucumberTest {
}
Note: You'll also need to tell Cucumber which class should be used to boot strap your application context. This class should also be on your glue path. For example:
import com.example.app;
import org.springframework.boot.test.context.SpringBootTest;
import io.cucumber.spring.CucumberContextConfiguration;
@CucumberContextConfiguration
@SpringBootTest(classes = TestConfig.class)
public class CucumberSpringConfiguration {
}