java - 在 Spring MVC 应用程序中使用 Selenium WebDriver 进行前端测试

标签 java spring-mvc selenium-webdriver tdd

我正在开发 spring mvc 应用程序,并尝试使用 selenium web 驱动程序测试我的前端以及 Controller 和前端之间的集成测试,引用 Spring MVC test with WebDriver 。本博客建议使用 MockMvcHtmlUnitDriver 作为 Web 驱动程序实现,以便使用 spring mvc 运行前端测试,而无需部署到服务器。 MVC 工作完全正常,MockMvcHtmlUnitDriver 也可以完美处理请求,但它无法获取前端页面。

这里是我为测试编写的代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-context.xml")
@WebAppConfiguration
public class WebDriverDemoTest {

@Autowired
private WebApplicationContext context;

private WebDriver driver;

@Before
public void setup() throws Exception {
    MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    
    this.driver = new MockMvcHtmlUnitDriver(mockMvc, true);
}

@Test
public void testFormCreation() {

    this.driver.get("http://localhost:8080/wddemo/demo");
    System.out.println(" - Page Title: " + this.driver.getTitle());
}}

在这里,您可以看到我正在尝试获取页面标题,但这些结果为空。

测试用例日志:

10:55:59,031 DEBUG TestDispatcherServlet:1218 - Rendering view      [org.springframework.web.servlet.view.JstlView: name 'spring'; URL [/spring.jsp]] in DispatcherServlet with name ''
10:55:59,038 DEBUG JstlView:207 - Forwarding to resource [/spring.jsp] in InternalResourceView 'spring'
10:55:59,039 DEBUG MockRequestDispatcher:67 - MockRequestDispatcher: forwarding to [/spring.jsp]
10:55:59,039 DEBUG TestDispatcherServlet:991 - Successfully completed request
 - Page Title: null

在此日志中,您可以看到 mvc 已完美处理,但 Web 驱动程序未获取页面。但是,在服务器中部署并使用 HtmlUnitDriver 可以按预期完美运行。

你们觉得这有什么问题吗?

最佳答案

从您的调试中我可以看到您正在使用 JSP。

来自part 1您引用的博客文章的内容:

NOTE: Just as with Spring MVC Test, the HtmlUnit integration will work with templating technologies that do not rely on a Servlet Container (i.e. Thymeleaf, Freemarker, Velocity, etc). It does not work with JSPs since they rely on the Servlet Container.

关于java - 在 Spring MVC 应用程序中使用 Selenium WebDriver 进行前端测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23751500/

相关文章:

java - 有没有办法编译隐藏源代码?

java - 删除所有小于 Elasticsearch 中的值的元素

java - 使用 hibernate 管理多对多关系

java - Android SDK 版本 23.6

spring-mvc - 如何将 Spring Boot 部署到 Cloud Foundry?

java - 用于字符串列表的 Initbinder

java - Spring:客户端发送的请求语法错误()

python - 在后台运行 webdriver selenium

python - Selenium (Python)+ react

javascript - 如何在创建文件的同一文件中调用 this.function