如何将正确的 Spring 上下文连接到我的 Cucumber 测试?

How do I wire up the correct Spring context to my Cucumber tests?

我的 Spring Web MVC 应用程序有一个工作集成测试,如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ShibaApplication.class)
@WebAppConfiguration
public class EchoControllerTests {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    private void setup() throws Exception {
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void echo() throws Exception {
        mockMvc.perform(get("/echo/blargh"))
            .andExpect(status().isOk())
            .andExpect(content().string("blargh"));
    }
}

留下那个(成功的)测试,我尝试创建一个相同的 Cucumber 测试。黄瓜亚军是:

@RunWith(Cucumber.class)
@CucumberOptions(features="src/test/resources",
                 glue={"co.masslab.shiba", "cucumber.api.spring"})
public class CucumberTests {
}

定义 Cucumber 步骤的 class 如下所示:

@WebAppConfiguration
@Import(ShibaApplication.class)
@ContextConfiguration(classes=CucumberTests.class)
public class WebStepDefs {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;
    private ResultActions resultActions;

    @When("^the client calls the echo endpoint$")
    public void the_client_calls() throws Exception {
        Assert.notNull(webApplicationContext);
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
        this.resultActions = mockMvc.perform(get("/echo/blargh"));
    }

    @Then("^the client receives a status code of 200$")
    public void the_client_receives_a_status_code() throws Exception {
        resultActions.andExpect(status().isOk());
    }
}

但是,黄瓜测试失败了,因为结果不是 200 而是 404。

我怀疑这是因为自动连接到 WebStepDefs class 的 WebApplicationContext 与自动连接到 EchoControllerTests 的不同。我一直在检查 Spring JavaConfig Reference Guide v1.0.0.M4,但我还没有弄清楚我哪里出错了。

我一直在尝试不同的注释组合,终于弄明白了这一点。对我有用的 WebStepsDef 注释是:

@ContextConfiguration(classes=ShibaApplication.class, loader=SpringApplicationContextLoader.class)
@IntegrationTest
@WebAppConfiguration