以下是代码:
我知道默认情况下,下面的代码会覆盖Button作为Mock对象的默认行为。所以它不会起作用。我坚持下去。
使用现有视图传递测试的最佳做法是什么?如何在匿名内部类中运行那个小部分视图呢?我如何模拟点击事件,但同时保持代码不变。
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwtmockito.GwtMock;
import com.google.gwtmockito.GwtMockitoTestRunner;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
@RunWith(GwtMockitoTestRunner.class)
public class ExceptionTest {
@GwtMock
private ClickHandler clickHandler;
@GwtMock
private Button btn;
private GUI gui;
@Before
public void setUp() {
when(btn.addClickHandler(any(ClickHandler.class))).thenAnswer(new Answer() {
public Object answer(InvocationOnMock aInvocation) throws Throwable {
clickHandler = (ClickHandler) aInvocation.getArguments()[0];
return null;
}
});
gui = new GUI();
}
@Test
public void runner() {
clickHandler.onClick(new ClickEvent(){});
Assert.assertEquals(1, gui.getSize());
}
}
GUI.java
class GUI extends FlowPanel {
private final Button button = new Button("OK");
private int size;
public GUI() {
button.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent clickEvent) {
size += 1;
}
});
}
public int getSize(){
return this.size;
}
}