Webのユニットテスト③ Java
前回の続きです。
SampleFormをテストするクラスを作ってみます。
SampleFormTest.java
Seleniumインスタンスを使って、ブラウザを操作しながらテストしていきます。
GUIアプリケーションのユニットテストとほぼ同じ感じですね。
ただ、ブラウザを操作しながらのテストなので、ブラウザの表示待ちを考慮する必要があります。
// ページ再表示まで待機 this.webTester.getSelenium().waitForPageToLoad("3000");
こんな感じでミリ秒指定で表示待ちを行っています。
ですが、ミリ秒指定で表示待ちを行うとタイミングによってはテストが失敗する事があります。
HTML要素が表示されるまで待つ処理にしておいた方が無難かも。
package sample; import org.junit.After; import org.junit.Before; import org.junit.Test; public class SampleFormTest { private DbTester dbTester = new DbTester(); private WebTester webTester = new WebTester(); @Before public void setUp() throws Throwable { // データベースの初期化 this.dbTester.setUp(Dbcp.getInstance().getConnection()); this.dbTester.initDb("testdata/SampleFormTest/init.xls"); // Seleniumの初期化 this.webTester.setUp(); } @After public void tearDown() throws Throwable { this.dbTester.tearDown(); this.webTester.tearDown(); } @Test public void clickSearchButton() throws Throwable { // ブラウザで表示 this.webTester.getSelenium().open(this.webTester.getWebAppName() + "/SampleForm.htm"); // 検索ボタン押下 this.webTester.getSelenium().click("検索"); // ページ再表示まで待機 this.webTester.getSelenium().waitForPageToLoad("3000"); // 表示されたテーブルを確認 String[][] expected = new String[][] { { "1", "userA" }, { "2", "userB" }, { "3", "userC" } }; HtmlTableAssert.assertEquals(this.webTester.getSelenium(), "table[@class='its']", expected); } }
Eclipseから実行してみる
プロジェクトを選択して右クリックメニューの[実行]→[サーバで実行]でTomcatを起動しておきます。
Eclipseからテストを実行してみます。実行方法は以前と同じです。
テストを実行するとSeleniumがブラウザを表示して、勝手に検索ボタンを押します。
わざとエラーにしてみます。
clickSearchButtonメソッドの期待値を変更して実行すると・・・
@Test public void clickSearchButton() throws Throwable { // ブラウザで表示 this.webTester.getSelenium().open(this.webTester.getWebAppName() + "/SampleForm.htm"); // 検索ボタン押下 this.webTester.getSelenium().click("検索"); // ページ再表示まで待機 this.webTester.getSelenium().waitForPageToLoad("3000"); // 表示されたテーブルを確認 //String[][] expected = new String[][] { { "1", "userA" }, { "2", "userB" }, { "3", "userC" } }; String[][] expected = new String[][] { { "1", "userA" }, { "2", "HOGEHOGE" }, { "3", "userC" } }; HtmlTableAssert.assertEquals(this.webTester.getSelenium(), "table[@class='its']", expected); }
ちゃんとエラーになりますね!