测试Ajax-在Apache Wicket中提交表单

时间:2017-01-19 13:09:26

标签: java ajax forms unit-testing wicket

假设我有一个如下所示的表单,它是通过Ajax提交的:

import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.markup.html.WebPage;

public class FormPage extends WebPage {
    public FormPage(final PageParameters parameters) {
        Form form = new Form("myForm");
        // Ajax submit
        form.add(new AjaxFormSubmitBehavior("onsubmit") {
            @Override
            protected void onSubmit(AjaxRequestTarget target) {
                super.onSubmit(target); // Breakpoint on this line
            }
        });
        add(form);
    }   
}

现在我需要测试表单,并在onSubmit方法中设置断点。这是测试代码:

import org.apache.wicket.util.tester.FormTester;
import org.apache.wicket.util.tester.WicketTester;
import org.junit.Before;
import org.junit.Test;

public class TestFormPage {
    private WicketTester tester;

    @Before
    public void setUp() {
        tester = new WicketTester(new WicketApplication());
    }

    @Test
    public void homepageRendersSuccessfully() {
        tester.startPage(FormPage.class);
        tester.assertRenderedPage(FormPage.class);

        FormTester formTester = tester.newFormTester("myForm");
        formTester.submit();        
    }
}

但问题是,当我运行单元测试时,永远不会达到设置断点的行。不知道出了什么问题?

1 个答案:

答案 0 :(得分:2)

在测试中,以下行将提交一个普通表单,但不会触发Ajax提交事件。

formTester.submit();

为了触发Ajax提交事件,应该使用WicketTester #cuteAjaxEvent,如下所示:

import org.apache.wicket.util.tester.WicketTester;
import org.junit.Before;
import org.junit.Test;

public class TestFormPage {
    private WicketTester tester;

    @Before
    public void setUp() {
        tester = new WicketTester(new WicketApplication());
    }

    @Test
    public void homepageRendersSuccessfully() {
        tester.startPage(FormPage.class);
        tester.assertRenderedPage(FormPage.class);

        tester.executeAjaxEvent("myForm", "submit");    
    }
}

价: