问题
I have begun to use cucumber tests for my Spring application. I set active Spring profile by passing jvm argument spring.profiles.active=testProfile.
Is there any way to do this programatically? Something like:
@RunWith(Cucumber.class)
@Cucumber.Options(...)
@ActiveProfiles("testProfile")
public class MyCucumberTest
Using cucumber 1.1.6
回答1:
I'm not sure this is the proper way to do it, but at least it get it working for me. I'm using cucumber version 1.2.4
I specialized the Cucumber junit runner to set the wanted spring profile in the constructor:
public class SpringProfileCucumber extends Cucumber {
public SpringProfileCucumber(Class clazz) throws InitializationError, IOException {
super(clazz);
System.setProperty("spring.profiles.active", "testProfile");
}
}
In the test use the SpringProfileCucumber junit runner
@RunWith(SpringProfileCucumber.class)
@CucumberOptions(features = {"src/test/java/tests/cucumber/test.feature"}, glue = { "tests.cucumber"})
public class MyCucumberTest {
// ... the test
}
回答2:
This is becoming out-dated. The use of cucumber.xml
is not applicable for cucumber-jvm.
I have a similar problem, trying to use:
@ActiveProfiles(value = "DEV", inheritProfiles = false)
@IfProfileValue(name= "ENV", value = "DEV")
with a command line of:
-DENV=DEV -Dspring.active.profiles=DEV
It seems that these directives don't work with the spring-cucumber library (1.1.5, at least).
回答3:
Extending on @perseger's answer, the following specialised runner allows you to use the @ActiveProfiles annotation
public class SpringProfileCucumber extends Cucumber {
public SpringProfileCucumber(Class clazz)
throws InitializationError, IOException {
super(clazz);
ActiveProfiles ap = (ActiveProfiles) clazz
.getAnnotation(ActiveProfiles.class);
if (ap != null) {
System.setProperty("spring.profiles.active",
String.join(",", ap.value()));
}
}
}
In the test, you can then use
@RunWith(SpringProfileCucumber.class)
@CucumberOptions(...)
@ActiveProfiles("testProfile")
public class RyvrTests {
}
回答4:
Alternatively, you can also create an annotation to activate a profile for cucumber. It looks like this:
import java.lang.annotation.*;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ContextConfiguration
@ActiveProfiles("test")
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = FeatureTestConfiguration.class)
public @interface FeatureFileSteps {
}
Quoted from my answer from this question:
How to activate spring boot profile with cucumber
来源:https://stackoverflow.com/questions/22612414/programatically-set-spring-profile-in-cucumber