環境
- macOS Monterey 12.4
- Google Chrome 103.0.5060.134
- JDK 17.0.1 (Eclipse Temurin)
- Spring Boot 2.7.1
- Selenide 6.6.6
Selenideとは
Seleniumを使いやすくしたラッパーライブラリだそうです。
公式サイト→ https://selenide.org/
依存性の追加
pom.xmlに、spring-boot-starter-testと共にselenideを追加します。
pom.xml
<dependencies>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.codeborne</groupId>
<artifactId>selenide</artifactId>
<version>6.6.6</version>
<scope>test</scope>
</dependency>
...
</dependencies>
以前のSpring Bootでは、Spring Boot自体がSeleniumに依存していたため、Seleniumのバージョンを指定し直す必要があったようです(参考記事)。しかし、少なくともSpring Boot 2.7ではSeleniumに依存していないため、そのような必要はありません。
Selenideの設定
src/test/resourcesにselenide.propertiesを作成して、次のように記述します。
selenide.properties
selenide.browser=chrome
selenide.headless=true
どのような設定項目があるかは、
com.codeborne.selenide.Configuration
クラスのJavadocをご確認ください。
テストコードの作成
Selenideの詳細なAPIは公式ドキュメントを参照してください、
MemoIntegrationTest.java
package com.example.springmemo.integration;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import static com.codeborne.selenide.Selenide.*;
import static com.codeborne.selenide.Condition.*;
import static com.codeborne.selenide.CollectionCondition.*;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MemoIntegrationTest {
@LocalServerPort
int port;
private String url(String path) {
return "http://localhost:%d%s".formatted(port, path);
}
@Test
@DisplayName("トップページにアクセスしたらメモが3件表示される")
void test01() {
open(url("/"));
String selector = ".tr-memo";
assertAll(
() -> $$(selector).shouldBe(size(3)),
() -> $(selector).shouldBe(matchText("1 あああ \\d{4}年\\d{1,2}月\\d{1,2}日 \\d{1,2}時\\d{1,2}分\\d{1,2}秒"))
);
}
}