我的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步骤的类看起来像:
@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类的WebApplicationContext与自动连接到EchoControllerTests的WebApplicationContext不同。我一直在看Spring JavaConfig Reference Guide v1.0.0.M4,但我还没弄明白我哪里出错了。
答案 0 :(得分:1)
我一直在尝试不同的注释组合,最后想出了这个。 WebStepsDef的注释对我有用:
@ContextConfiguration(classes=ShibaApplication.class, loader=SpringApplicationContextLoader.class)
@IntegrationTest
@WebAppConfiguration