How to run an click event on simple GWT Button via Mockito and make the Test pass

532 Views Asked by At

Here is the code:

I know by default this code below overrides the default behavier of the Button as Mock object. So it won't work. I stuck on that.

What's the best practice to pass the Test with an already existing view like that ? How can I run that small part of view within an anonymous inner class like that ? How can I simulate the click event but at the same time keep the code like it is.

  1. I don't want to have a seperate getter, just to invoke button.click() method


    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;
        }
    }
0

There are 0 best solutions below