GwtMockito - 许多按钮的点击处理程序

GwtMockito - click handlers for many buttons

我对 GwtMock 和点击处理程序有疑问。

在我的单元测试中,我有一个包含 ClickHandler 和 Button 的字段:

@GwtMock 私人 ClickHandler clickHandler;

我的设置方法如下所示:

@Before
public void setUp() {
    when(this.display.getClearButton()).thenReturn(this.button);
    when(this.display.getChangeStatusButton()).thenReturn(this.button);
}

我的测试如下:

@Test
    public void shouldClearFilterAfterClickClearFilterButton() {
        // given
        when(this.button.addClickHandler(any(ClickHandler.class))).thenAnswer(new Answer<Object>() {
            public Object answer(InvocationOnMock aInvocation) throws Throwable {
                clickHandler = (ClickHandler) aInvocation.getArguments()[0];
                return null;
            }
        });

        this.presenter = new PresenterImpl(this.display, this.messages);

        // when
        clickHandler.onClick(clickEvent);


        // then
        this.presenter.asWidget();

    }

我想测试的代码看起来像(我从构造函数调用这个方法):

private void addHandlers() {



    this.display.getClearButton().addClickHandler(new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                    clearFilter();
                }
            });
            this.display.getChangeStatusButton().addClickHandler(new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                    changeStatus();
                }
            });
        }

问题是,当我 运行 进行单元测试时,我在按钮 "ChangeStatus" 上创建了一个点击事件,但我想在按钮 "Clear"

上创建一个点击事件

有趣的是,当我更改声明处理程序的顺序时,我可以通过 "Clear" 按钮调用代码

如何解决这个问题?如何调用特定按钮的点击事件?

让我们一起阅读该代码:

  1. 每当调用 getClearButton()getChangeStatusButton() 时,return this.button;也就是说,两个方法调用的按钮完全相同,这意味着您将无法分辨哪个是哪个:它们是一样的。
  2. 每当在该模拟按钮上调用 addClickHandler 时,将点击处理程序存储在一个字段中;也就是说,如果 addClickHandler 被调用两次,第二次调用将用第二个点击处理程序覆盖该字段,您将不再引用第一个。
  3. 被测代码同时调用 getClearButton()getChangeStatusButton() 并在两者上调用 addClickHandler;也就是说,在 this.button.
  4. 上调用 addClickHandler 两次

The problem is that when I run a unit test I make a click event on button "ChangeStatus" but I want make a click event on button "Clear"

What is interesting when I change order of declaration handler then I can invoke code over the "Clear" button

是的,这正是您的代码所预期的行为。如果您想区分按钮,请使用不同的模拟按钮。


IMO,更好的方法是: * 制作 getClearButtongetChangeStatusButton return HasClickHandlers,所以你甚至不需要 GwtMockito 并且可以只使用裸 Mockito。 * 重构您的代码,以便视图添加点击处理程序,将演示者传递给视图,因此视图可以从点击处理程序(例如 presenter.clear()presenter.changeStatus())调用演示者方法。因此,对于您的演示者测试,您只需调用演示者方法即可。同样,您不再需要 gwtMockito,只需使用裸 Mockito。参见 http://www.gwtproject.org/articles/mvp-architecture-2.html

AFAICT,GwtMockito 更适合您不在代码中分离视图和演示者的情况,而是使用 UiBinder 和 Java class 扮演演示者的角色,并且.ui.xml 是视图。