【发布时间】:2013-12-21 09:51:01
【问题描述】:
我正在使用 spring boot,因为它消除了所有无聊的东西,让我专注于我的代码,但是所有测试示例都使用 junit,我想使用 cucumber?
谁能指出我正确的方向,让黄瓜和弹簧启动,做所有的自动配置和连线,让我的步骤定义使用自动连线的 bean 来做事?
【问题讨论】:
我正在使用 spring boot,因为它消除了所有无聊的东西,让我专注于我的代码,但是所有测试示例都使用 junit,我想使用 cucumber?
谁能指出我正确的方向,让黄瓜和弹簧启动,做所有的自动配置和连线,让我的步骤定义使用自动连线的 bean 来做事?
【问题讨论】:
尝试在步骤定义类中使用以下内容:
@ContextConfiguration(classes = YourBootApplication.class,
loader = SpringApplicationContextLoader.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class MySteps {
//...
}
还要确保你的类路径中有 cucumber-spring 模块。
【讨论】:
Jake - 我的最终代码在每个黄瓜步骤定义类扩展的超类中有以下注释,这可以访问基于 Web 的模拟,添加各种测试范围,并且仅引导 Spring 启动一次。
@ContextConfiguration(classes = {MySpringConfiguration.class}, loader = SpringApplicationContextLoader.class)
@WebAppConfiguration
@TestExecutionListeners({WebContextTestExecutionListener.class,ServletTestExecutionListener.class})
WebContextTestExecutionListener 在哪里:
public class WebContextTestExecutionListener extends
AbstractTestExecutionListener {
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
if (testContext.getApplicationContext() instanceof GenericApplicationContext) {
GenericApplicationContext context = (GenericApplicationContext) testContext.getApplicationContext();
ConfigurableListableBeanFactory beanFactory = context
.getBeanFactory();
Scope requestScope = new RequestScope();
beanFactory.registerScope("request", requestScope);
Scope sessionScope = new SessionScope();
beanFactory.registerScope("session", sessionScope);
}
}
}
【讨论】:
我的方法很简单。在 Before 钩子中(在 env.groovy 中,因为我正在使用 Cucumber-JVM for Groovy),执行以下操作。
package com.example.hooks
import static cucumber.api.groovy.Hooks.Before
import static org.springframework.boot.SpringApplication.exit
import static org.springframework.boot.SpringApplication.run
def context
Before {
if (!context) {
context = run Application
context.addShutdownHook {
exit context
}
}
}
【讨论】:
感谢@PaulNUK,我找到了一组可行的注释。
我在我的问题here中发布了答案
我的 StepDefs 类需要注释:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = DemoApplication.class, loader = SpringApplicationContextLoader.class)
@WebAppConfiguration
@IntegrationTest
我链接的答案中还有一个包含源代码的存储库。
【讨论】: