|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
MockMvc 与 WebDriver
在前几节中,我们已经看到了如何使用MockMvc结合原始的HtmlUnit API。在本节中,我们将使用Selenium中的WebDriver的额外抽象来使事情变得更加简单。
为什么使用WebDriver和MockMvc?
我们已经可以使用HtmlUnit和MockMvc,那么为什么还要使用WebDriver呢?Selenium WebDriver提供了一个非常优雅的API,让我们可以轻松地组织代码。为了更好地展示它是如何工作的,我们在本节中探索一个示例。
| 尽管是Selenium的一部分,WebDriver 运行测试不需要 Selenium Server。 |
假设我们需要确保消息被正确创建。测试涉及找到 HTML 表单输入元素,填写这些元素,并进行各种断言。
这种方法会导致大量的单独测试,因为我们还想测试错误条件。例如,我们希望确保如果只填写表单的一部分,会收到错误提示。如果我们填写了整个表单,新创建的消息应该在之后显示。
如果其中一个字段被命名为“summary”,我们可能会在测试的多个地方看到类似于以下内容的重复:
-
Java
-
Kotlin
HtmlTextInput summaryInput = currentPage.getHtmlElementById("summary");
summaryInput.setValueAttribute(summary);
val summaryInput = currentPage.getHtmlElementById("summary")
summaryInput.setValueAttribute(summary)
那么如果我们把 id 改为 smmry 会发生什么?这样做将迫使我们更新所有测试以包含这个更改。这违反了DRY原则,因此我们最好将这段代码提取到自己的方法中,如下所示:
-
Java
-
Kotlin
public HtmlPage createMessage(HtmlPage currentPage, String summary, String text) {
setSummary(currentPage, summary);
// ...
}
public void setSummary(HtmlPage currentPage, String summary) {
HtmlTextInput summaryInput = currentPage.getHtmlElementById("summary");
summaryInput.setValueAttribute(summary);
}
fun createMessage(currentPage: HtmlPage, summary:String, text:String) :HtmlPage{
setSummary(currentPage, summary);
// ...
}
fun setSummary(currentPage:HtmlPage , summary: String) {
val summaryInput = currentPage.getHtmlElementById("summary")
summaryInput.setValueAttribute(summary)
}
这样做可以确保我们在更改 UI 时不必更新所有测试。
我们甚至可以更进一步,将此逻辑放置在一个 Object 中,该 HtmlPage 表示我们当前所在的上下文,如下例所示:
-
Java
-
Kotlin
public class CreateMessagePage {
final HtmlPage currentPage;
final HtmlTextInput summaryInput;
final HtmlSubmitInput submit;
public CreateMessagePage(HtmlPage currentPage) {
this.currentPage = currentPage;
this.summaryInput = currentPage.getHtmlElementById("summary");
this.submit = currentPage.getHtmlElementById("submit");
}
public <T> T createMessage(String summary, String text) throws Exception {
setSummary(summary);
HtmlPage result = submit.click();
boolean error = CreateMessagePage.at(result);
return (T) (error ? new CreateMessagePage(result) : new ViewMessagePage(result));
}
public void setSummary(String summary) throws Exception {
summaryInput.setValueAttribute(summary);
}
public static boolean at(HtmlPage page) {
return "Create Message".equals(page.getTitleText());
}
}
class CreateMessagePage(private val currentPage: HtmlPage) {
val summaryInput: HtmlTextInput = currentPage.getHtmlElementById("summary")
val submit: HtmlSubmitInput = currentPage.getHtmlElementById("submit")
fun <T> createMessage(summary: String, text: String): T {
setSummary(summary)
val result = submit.click()
val error = at(result)
return (if (error) CreateMessagePage(result) else ViewMessagePage(result)) as T
}
fun setSummary(summary: String) {
summaryInput.setValueAttribute(summary)
}
fun at(page: HtmlPage): Boolean {
return "Create Message" == page.getTitleText()
}
}
}
以前,这种模式被称为 页面对象模式。虽然我们当然可以用HtmlUnit来实现这一点,但WebDriver提供了一些我们在接下来的章节中将要探讨的工具,使得实现这种模式变得更加容易。
MockMvc 和 WebDriver 配置
要使用Selenium WebDriver与Spring MVC Test框架,请确保您的项目包含对org.seleniumhq.selenium:selenium-htmlunit-driver的测试依赖。
我们可以轻松地创建一个与MockMvc集成的Selenium WebDriver,如下例所示:
-
Java
-
Kotlin
WebDriver driver;
@BeforeEach
void setup(WebApplicationContext context) {
driver = MockMvcHtmlUnitDriverBuilder
.webAppContextSetup(context)
.build();
}
lateinit var driver: WebDriver
@BeforeEach
fun setup(context: WebApplicationContext) {
driver = MockMvcHtmlUnitDriverBuilder
.webAppContextSetup(context)
.build()
}
这是一个使用MockMvcHtmlUnitDriverBuilder的简单示例。有关更高级的用法,请参阅高级MockMvcHtmlUnitDriverBuilder。 |
前一个示例确保任何引用localhost作为服务器的URL都会被定向到我们的MockMvc实例,而无需实际的HTTP连接。其他任何URL都通过网络连接正常请求。这使我们能够轻松测试CDN的使用。
MockMvc 和 WebDriver 的使用
现在我们可以像平常一样使用WebDriver,但不需要将我们的应用程序部署到Servlet容器中。例如,我们可以请求视图创建一条消息,如下所示:
-
Java
-
Kotlin
CreateMessagePage page = CreateMessagePage.to(driver);
val page = CreateMessagePage.to(driver)
然后我们可以填写表单并提交以创建消息,如下所示:
-
Java
-
Kotlin
ViewMessagePage viewMessagePage =
page.createMessage(ViewMessagePage.class, expectedSummary, expectedText);
val viewMessagePage =
page.createMessage(ViewMessagePage::class, expectedSummary, expectedText)
这改进了我们HtmlUnit测试的设计,通过利用页面对象模式。正如我们在为什么选择WebDriver和MockMvc?中提到的,我们可以使用页面对象模式与HtmlUnit一起工作,但使用WebDriver会更容易。考虑以下CreateMessagePage实现:
-
Java
-
Kotlin
public class CreateMessagePage extends AbstractPage { (1)
(2)
private WebElement summary;
private WebElement text;
@FindBy(css = "input[type=submit]") (3)
private WebElement submit;
public CreateMessagePage(WebDriver driver) {
super(driver);
}
public <T> T createMessage(Class<T> resultPage, String summary, String details) {
this.summary.sendKeys(summary);
this.text.sendKeys(details);
this.submit.click();
return PageFactory.initElements(driver, resultPage);
}
public static CreateMessagePage to(WebDriver driver) {
driver.get("http://localhost:9990/mail/messages/form");
return PageFactory.initElements(driver, CreateMessagePage.class);
}
}
| 1 | CreateMessagePage 扩展了 AbstractPage。我们不会深入讨论 AbstractPage 的细节,但简而言之,它包含了我们所有页面的通用功能。例如,如果我们的应用程序有一个导航栏、全局错误消息和其他功能,我们可以将这些逻辑放在一个共享的位置。 |
| 2 | 我们有一个成员变量对应于我们感兴趣的HTML页面的每一部分。这些是WebElement类型的。WebDriver的
PageFactory让我们可以从HtmlUnit版本的CreateMessagePage中删除大量代码,通过自动解析每个WebElement。The
PageFactory#initElements(WebDriver,Class<T>)
方法通过使用字段名称并在HTML页面内查找id或name来自动解析每个WebElement。 |
| 3 | 我们可以使用
@FindBy 注解
来覆盖默认查找行为。本示例展示了如何通过 @FindBy
注解使用 css 选择器(input[type=submit])查找提交按钮。 |
class CreateMessagePage(private val driver: WebDriver) : AbstractPage(driver) { (1)
(2)
private lateinit var summary: WebElement
private lateinit var text: WebElement
@FindBy(css = "input[type=submit]") (3)
private lateinit var submit: WebElement
fun <T> createMessage(resultPage: Class<T>, summary: String, details: String): T {
this.summary.sendKeys(summary)
text.sendKeys(details)
submit.click()
return PageFactory.initElements(driver, resultPage)
}
companion object {
fun to(driver: WebDriver): CreateMessagePage {
driver.get("http://localhost:9990/mail/messages/form")
return PageFactory.initElements(driver, CreateMessagePage::class.java)
}
}
}
| 1 | CreateMessagePage 扩展了 AbstractPage。我们不会深入讨论 AbstractPage 的细节,但简而言之,它包含了我们所有页面的通用功能。例如,如果我们的应用程序有一个导航栏、全局错误消息和其他功能,我们可以将这些逻辑放在一个共享的位置。 |
| 2 | 我们有一个成员变量对应于我们感兴趣的HTML页面的每一部分。这些是WebElement类型的。WebDriver的
PageFactory让我们可以从HtmlUnit版本的CreateMessagePage中删除大量代码,通过自动解析每个WebElement。The
PageFactory#initElements(WebDriver,Class<T>)
方法通过使用字段名称并在HTML页面内查找id或name来自动解析每个WebElement。 |
| 3 | 我们可以使用
@FindBy 注解
来覆盖默认的查找行为。我们的示例展示了如何使用 @FindBy
注解通过 css 选择器(input[type=submit])查找我们的提交按钮。 |
最后,我们可以验证新消息是否成功创建。以下断言使用了AssertJ断言库:
-
Java
-
Kotlin
assertThat(viewMessagePage.getMessage()).isEqualTo(expectedMessage);
assertThat(viewMessagePage.getSuccess()).isEqualTo("Successfully created a new message");
assertThat(viewMessagePage.message).isEqualTo(expectedMessage)
assertThat(viewMessagePage.success).isEqualTo("Successfully created a new message")
我们可以看到我们的 ViewMessagePage 让我们能够与自定义的领域模型进行交互。例如,它暴露了一个返回 Message 对象的方法:
-
Java
-
Kotlin
public Message getMessage() throws ParseException {
Message message = new Message();
message.setId(getId());
message.setCreated(getCreated());
message.setSummary(getSummary());
message.setText(getText());
return message;
}
fun getMessage() = Message(getId(), getCreated(), getSummary(), getText())
然后我们可以在断言中使用丰富的领域对象。
最后,我们不能忘记在测试完成时关闭 WebDriver 实例,如下所示:
-
Java
-
Kotlin
@AfterEach
void destroy() {
if (driver != null) {
driver.close();
}
}
@AfterEach
fun destroy() {
if (driver != null) {
driver.close()
}
}
有关使用WebDriver的更多信息,请参阅Selenium WebDriver文档。
高级 MockMvcHtmlUnitDriverBuilder
在到目前为止的例子中,我们以最简单的方式使用了MockMvcHtmlUnitDriverBuilder,通过基于Spring TestContext Framework为我们加载的WebApplicationContext来构建一个WebDriver。以下是重复这一方法的示例:
-
Java
-
Kotlin
WebDriver driver;
@BeforeEach
void setup(WebApplicationContext context) {
driver = MockMvcHtmlUnitDriverBuilder
.webAppContextSetup(context)
.build();
}
lateinit var driver: WebDriver
@BeforeEach
fun setup(context: WebApplicationContext) {
driver = MockMvcHtmlUnitDriverBuilder
.webAppContextSetup(context)
.build()
}
我们还可以指定其他配置选项,如下:
-
Java
-
Kotlin
WebDriver driver;
@BeforeEach
void setup() {
driver = MockMvcHtmlUnitDriverBuilder
// demonstrates applying a MockMvcConfigurer (Spring Security)
.webAppContextSetup(context, springSecurity())
// for illustration only - defaults to ""
.contextPath("")
// By default MockMvc is used for localhost only;
// the following will use MockMvc for example.com and example.org as well
.useMockMvcForHosts("example.com","example.org")
.build();
}
lateinit var driver: WebDriver
@BeforeEach
fun setup() {
driver = MockMvcHtmlUnitDriverBuilder
// demonstrates applying a MockMvcConfigurer (Spring Security)
.webAppContextSetup(context, springSecurity())
// for illustration only - defaults to ""
.contextPath("")
// By default MockMvc is used for localhost only;
// the following will use MockMvc for example.com and example.org as well
.useMockMvcForHosts("example.com","example.org")
.build()
}
作为替代方案,我们可以通过单独配置MockMvc实例并将其提供给MockMvcHtmlUnitDriverBuilder来执行完全相同的设置,如下所示:
-
Java
-
Kotlin
MockMvc mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
driver = MockMvcHtmlUnitDriverBuilder
.mockMvcSetup(mockMvc)
// for illustration only - defaults to ""
.contextPath("")
// By default MockMvc is used for localhost only;
// the following will use MockMvc for example.com and example.org as well
.useMockMvcForHosts("example.com","example.org")
.build();
// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed
这是更冗长的,但是,通过使用MockMvc实例构建WebDriver,我们掌握了MockMvc的全部功能。
有关创建MockMvc实例的更多信息,请参阅
设置选项。 |