此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

MockMvc 和 WebDriver

在前面的部分中,我们已经了解了如何将 MockMvc 与原始 HtmlUnit API 的 API。在本节中,我们在 Selenium WebDriver 中使用其他抽象来使事情变得更加容易。spring-doc.cadn.net.cn

为什么选择 WebDriver 和 MockMvc?

我们已经可以使用 HtmlUnit 和 MockMvc,那么我们为什么要使用 WebDriver?这 Selenium WebDriver 提供了一个非常优雅的 API,让我们可以轻松组织代码。自 更好地展示它是如何工作的,我们将在本节中探讨一个示例。spring-doc.cadn.net.cn

尽管是 Selenium 的一部分,但 WebDriver 没有 需要 Selenium 服务器来运行您的测试。

假设我们需要确保正确创建消息。测试涉及发现 HTML 表单输入元素,填写它们,并做出各种断言。spring-doc.cadn.net.cn

这种方法会导致许多单独的测试,因为我们想要测试错误条件 也。例如,我们希望确保如果我们只填写部分 表格。如果我们填写整个表格,则应显示新创建的消息 之后。spring-doc.cadn.net.cn

如果其中一个字段被命名为“summary”,我们可能会有类似于 以下在我们的测试中的多个地方重复:spring-doc.cadn.net.cn

HtmlTextInput summaryInput = currentPage.getHtmlElementById("summary");
summaryInput.setValueAttribute(summary);
val summaryInput = currentPage.getHtmlElementById("summary")
summaryInput.setValueAttribute(summary)

那么,如果我们将idsmmry?这样做将迫使我们更新所有 纳入这一变化的测试。这违反了 DRY 原则,所以我们应该 理想情况下,将此代码提取到自己的方法中,如下所示:spring-doc.cadn.net.cn

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 时不必更新所有测试。spring-doc.cadn.net.cn

我们甚至可以更进一步,将此逻辑放在Object那 表示HtmlPage我们当前处于 ON,如以下示例所示:spring-doc.cadn.net.cn

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 提供了一些我们在 以下部分将使此模式更易于实现。spring-doc.cadn.net.cn

MockMvc 和 WebDriver 设置

将 Selenium WebDriver 与MockMvc,请确保您的项目包含测试 依赖于org.seleniumhq.selenium:htmlunit3-driver.spring-doc.cadn.net.cn

我们可以轻松创建一个与 MockMvc 集成的 Selenium WebDriver,方法是使用MockMvcHtmlUnitDriverBuilder如以下示例所示:spring-doc.cadn.net.cn

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.

前面的示例可确保引用的任何 URLlocalhost因为服务器是 直接发送给我们的MockMvc实例,无需真正的 HTTP 连接。任何其他 像往常一样,使用网络连接请求 URL。这使我们可以轻松地测试 CDN 的使用。spring-doc.cadn.net.cn

MockMvc 和 WebDriver 的使用

现在我们可以像往常一样使用 WebDriver,但无需部署我们的 应用程序添加到 Servlet 容器中。例如,我们可以请求视图创建一个 消息,其中包含以下内容:spring-doc.cadn.net.cn

CreateMessagePage page = CreateMessagePage.to(driver);
val page = CreateMessagePage.to(driver)

然后,我们可以填写表格并提交以创建消息,如下所示:spring-doc.cadn.net.cn

ViewMessagePage viewMessagePage =
		page.createMessage(ViewMessagePage.class, expectedSummary, expectedText);
val viewMessagePage =
	page.createMessage(ViewMessagePage::class, expectedSummary, expectedText)

这通过利用页面对象模式改进了 HtmlUnit 测试的设计。正如我们在为什么选择 WebDriver 和 MockMvc?中提到的,我们可以使用页面对象模式 使用 HtmlUnit,但使用 WebDriver 要容易得多。考虑以下几点CreateMessagePage实现:spring-doc.cadn.net.cn

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.这PageFactory#initElements(WebDriver,Class<T>)方法会自动解析每个WebElement通过使用字段名称并查找它 通过idnameHTML 页面中的元素。
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.这PageFactory#initElements(WebDriver,Class<T>)方法会自动解析每个WebElement通过使用字段名称并查找它 通过idnameHTML 页面中的元素。
3 我们可以使用@FindBy注解以覆盖默认查找行为。我们的示例展示了如何使用@FindBy注释来查找我们的提交按钮,并带有css选择器 (input[type=submit])。

最后,我们可以验证新消息是否已成功创建。以下内容 断言使用 AssertJ 断言库:spring-doc.cadn.net.cn

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对象:spring-doc.cadn.net.cn

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())

然后,我们可以在断言中使用富域对象。spring-doc.cadn.net.cn

最后,我们不能忘记关闭WebDriver实例,当测试完成时, 如下:spring-doc.cadn.net.cn

@AfterEach
void destroy() {
	if (driver != null) {
		driver.close();
	}
}
@AfterEach
fun destroy() {
	if (driver != null) {
		driver.close()
	}
}

有关使用 WebDriver 的更多信息,请参阅 Selenium WebDriver 文档spring-doc.cadn.net.cn

高深MockMvcHtmlUnitDriverBuilder

在到目前为止的示例中,我们使用了MockMvcHtmlUnitDriverBuilder以最简单的方式 可能,通过构建一个WebDriver基于WebApplicationContext为我们加载 Spring TestContext 框架。此处重复此方法,如下所示:spring-doc.cadn.net.cn

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

我们还可以指定其他配置选项,如下所示:spring-doc.cadn.net.cn

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如下:spring-doc.cadn.net.cn

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 {kotlin-issues}/KT-22208 is fixed

这更冗长,但是,通过构建WebDriver使用MockMvc实例,我们有 MockMvc 的全部功能触手可及。spring-doc.cadn.net.cn

有关创建MockMvc实例,请参阅配置 MockMvc