4

我将 GWT 2.4 与 JUnit 4.8.1 一起使用。在编写扩展 GWTTestCase 的类时,我想模拟单击页面上的按钮。目前,在我的 onModuleLoad 方法中,这个按钮只是一个本地字段......

public void onModuleLoad() {
    final Button submitButton = Button.wrap(Document.get().getElementById(SUBMIT_BUTTON_ID));
    ...     

    // Add a handler to send the name to the server
    GetHtmlHandler handler = new GetHtmlHandler();
    submitButton.addClickHandler(handler);

如何从 GWTTestCase 模拟单击​​此按钮?我是否必须将此按钮公开为公共成员访问器是否有更优雅的方式来访问它?到目前为止,这是我的测试用例中的内容...

public class GetHtmlTest extends GWTTestCase {

    // Entry point class of the GWT application being tested.
    private Productplus_gwt productPlusModule;

    @Override
    public String getModuleName() {
        return "com.myco.clearing.productplus.Productplus_gwt";
    }

    @Before
    public void prepareTests() { 
        productPlusModule = new Productplus_gwt();
        productPlusModule.onModuleLoad();
    }   // setUp

    @Test
    public void testSuccessEvent() { 
        // TODO:  Simulate clicking on button
    }   // testSuccessEvent

}

谢谢, - 戴夫

4

3 回答 3

2

gwt-test-utils似乎是满足您需求的完美框架。不要从GWTTestCase继承,而是扩展 gwt-test-utils GwtTest类并使用 Browser 类实现您的点击测试,如入门指南中所示:

  @Test
public void checkClickOnSendMoreThan4chars() {
   // Arrange
   Browser.fillText(app.nameField, "World");

   // Act
   Browser.click(app.sendButton);

   // Assert
   assertTrue(app.dialogBox.isShowing());
   assertEquals("", app.errorLabel.getText());
   assertEquals("Hello, World!", app.serverResponseLabel.getHTML());
   assertEquals("Remote Procedure Call", app.dialogBox.getText());
}

如果你想让你的按钮保持私密,你可以通过自省来检索它。但我的建议是让您查看受保护的小部件包,并在同一个包中编写单元测试,以便它可以访问它们。它更加方便和重构友好。

gwt-test-utils 提供自省的说服力。例如,要检索可能是私有的“对话框”字段,您可以这样做:

 DialogBox dialogBox = GwtReflectionUtils.getPrivateFieldValue(app, "dialogBox");

但请注意,使用 GwtReflectionUtils 不是强制性的。gwt-test-utils 允许您在 GWT 客户端测试中使用任何 java 类,没有限制:)

于 2011-10-31T13:44:59.443 回答
2

它可以像buttonElement.click()(or ButtonElement.as(buttonWidget.getElement()).click(), or ButtonElement.as(Document.get().getElementById(SUBMIT_BUTTON_ID)).click())一样简单

但请记住,GWTTestCase 不会在您自己的 HTML 主机页面中运行,而是在一个空页面中运行,因此您必须首先在页面中插入按钮,然后才能模拟模块的加载。

于 2011-10-28T17:06:58.253 回答
0

你可以这样做:

YourComposite view = new YourComposite();
RootPanel.get().add(view);

view.getSubmitButton.getElement().<ButtonElement>cast().click();
于 2013-01-07T05:26:54.853 回答