【发布时间】:2018-03-28 06:42:48
【问题描述】:
我编写了以下简单的测试用例来测试 MockMvc 和 WebDriver:
@RunWith(SpringRunner.class)
@WebAppConfiguration("/src/main/resources")
@ContextConfiguration(classes = {MvcConfig.class})
public class exampleTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
private WebDriver driver;
@Before
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
this.driver = MockMvcHtmlUnitDriverBuilder.webAppContextSetup(this.context).build();
}
@Test
public void mvcTest() throws Exception {
mvc.perform(get("/")).andExpect(status().isOk());
}
@Test
public void driverTest() {
this.driver.get("http://localhost:8080/");
assertEquals("Please log in", this.driver.findElement(By.xpath("/html/body/form/h1")).getText());
}
}
如果我执行它,我会得到 java.lang.NoClassDefFoundError: org/openqa/selenium/remote/SessionNotFoundException,这是 MockMvcHtmlUnitBuilder 在 before 方法中抛出的。如果我删除引发错误的行和驱动程序测试,mvcTest 不会成功,因为它得到的是 404 而不是 200。
所以我接下来要做的是删除 @WebAppConfiguration("/src/main/resources") 和 @ContextConfiguration(classes = {MvcConfig.class}) 注释并添加 @SpringBootTest(classes = Application.class) 注释。现在 mvcTest 可以工作了,但是如果我再次为驱动程序添加代码,它仍然会抛出 SessionNotFoundException。
所以我的问题是,如何在 Spring 5 中正确创建 MockMvc 和 WebDriver?
【问题讨论】:
标签: java spring spring-mvc spring-boot testing