お仕事で作っているwebアプリケーションはAjaxごりっごり取り入れているのですが、残念ながらWicketTesterでAjaxまわりのテストはできないのです。と、あるのですが、WicketTesterからAjaxまわりをテストする方法はあります。Wicketのユーザーの端くれとして、誤解をといておこうと思います。
サンプルは以下3つのファイルで構成されています。
- MyPage.html
- MyPage.java
- MyPageTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>ajax</title> | |
</head> | |
<body> | |
<form wicket:id="form"> | |
<input type="text" wicket:id="num1"/> | |
<span wicket:id="num2"/> | |
</form> | |
</body> | |
</html> |
MyPage.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.wicket.markup.html.form.TextField; | |
import org.apache.wicket.model.PropertyModel; | |
public class MyPage extends WebPage { | |
private Form<Void> form; | |
private Label label1; | |
private TextField<Integer> field; | |
private Integer num1; | |
private Integer num2; | |
public MyPage() { | |
form = new Form<Void>("form"); | |
field = new TextField<Integer>("num1", Integer.class); | |
label1 = new Label("num2"); | |
} | |
@Override | |
protected void onInitialize() { | |
super.onInitialize(); | |
super.add(form); | |
form.add(field); | |
form.add(label1); | |
field.setModel(new PropertyModel<Integer>(this, "num1")); | |
label1.setDefaultModel(new PropertyModel<Integer>(this, "num2")); | |
label1.setOutputMarkupId(true); | |
field.add(new OnChangeAjaxBehavior() { | |
@Override | |
protected void onUpdate(AjaxRequestTarget target) { | |
if(null != num1){ | |
num2 = num1 * num1; | |
} | |
target.add(label1); | |
} | |
private static final long serialVersionUID = 1L; | |
}); | |
} | |
private static final long serialVersionUID = 1L; | |
} |
MyPageTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ajaxtest; | |
import org.apache.wicket.util.tester.FormTester; | |
import org.apache.wicket.util.tester.WicketTester; | |
import org.junit.Before; | |
import org.junit.Test; | |
public class MyPageTest { | |
private WicketTester tester; | |
@Before | |
public void setUp() { | |
this.tester = new WicketTester(); | |
this.tester.startPage(MyPage.class); | |
} | |
@Test | |
public void num1入力() { | |
FormTester ft = this.tester.newFormTester("form"); | |
ft.setValue("num1", "12"); | |
this.tester.executeAjaxEvent("form:num1", "onchange"); | |
this.tester.assertLabel("form:num2", "144"); | |
} | |
} |
Javadoc:BaseWicketTester.executeAjaxEvent
これでAjaxもテストできます。よかったですね。