Jason Whittle
Jason Whittle

Reputation: 805

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

I have a working integration test for my Spring Web MVC app that looks like this:

@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"));
    }
}

Leaving that (successful) test in place, I tried to create an identical Cucumber test. The Cucumber runner is:

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

The class that defines the Cucumber steps looks like:

@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());
    }
}

However, the cucumber test fails, as the result is not a 200 but a 404.

I suspect this is because the WebApplicationContext getting autowired into the WebStepDefs class isn’t the same as the one that gets autowired into the EchoControllerTests. I’ve been going over the Spring JavaConfig Reference Guide v1.0.0.M4, but I haven’t yet figured out where I’m going wrong.

Upvotes: 0

Views: 1841

Answers (1)

Jason Whittle
Jason Whittle

Reputation: 805

I kept trying different combinations of annotations, and finally figured this one out. The annotations for WebStepsDef that worked for me were:

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

Upvotes: 1

Related Questions