ramon_salla
ramon_salla

Reputation: 1607

GWT testing with mockito

Simple Question:

Verification (1) passes. Verification (2) does not. Why? How to fix it?

Test

  @Test
    public void test() {
            System.out.println("test");
            EventBus eb = mock(EventBus.class);
            MyWidget.View v = mock(MyWidget.View.class);
            GreetingServiceAsync s = mock(GreetingServiceAsync.class);

            HasClickHandlers button = mock(HasClickHandlers.class);

            when(v.getButton()).thenReturn(button);

            new MyWidget(eb, v, s);

            button.fireEvent(mock(ClickEvent.class));   

            verify(button).addClickHandler(any(ClickHandler.class)); (1)
            verify(v).alert(anyString()); (2)


        }

Widget

@Inject
    public MyWidget(EventBus eventBus, View view, GreetingServiceAsync service){
        this.view = view;
        this.service = service;

        bindView();
        bindEventBus();

    }

    private void bindView(){

        view.getButton().addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                view.alert("test");
            }
        });

    }

Upvotes: 0

Views: 1839

Answers (4)

Flying Dutch Boy
Flying Dutch Boy

Reputation: 354

As David Wallace said, you are mocking the button. It does lose all its abilities. you could fix this by making a ArgumentCatptor

ArgumentCaptor<ClickHandler> captor = ArgumentCaptor.forClass(ClickHandler.class);

Then manually fire the function of the event by using:

captor.getValue().onClick(null);

This will fake the call that should have been made by the button.

If your class only has one button or one catcher for a specific event you can make it extend the ClickHandler class. Then you can just call the onClick of your class.

Upvotes: 0

ramon_salla
ramon_salla

Reputation: 1607

That is what I did:

public class ClickableElement implements HasClickHandlers{

        ClickHandler ch;
        @Override
        public void fireEvent(GwtEvent<?> event) {
            ch.onClick((ClickEvent) event);
        }

        @Override
        public HandlerRegistration addClickHandler(ClickHandler handler) {
            this.ch = handler;
            return null;        
        }

    };

Upvotes: 0

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

because button is a mock, so calling fireEvent on it doesn't actually fire the event; and onClick is never called on the view.

Upvotes: 3

checketts
checketts

Reputation: 14963

Because Button was mocked out and there is no implementation telling it what to do when fireEvent is called. See the line:

HasClickHandlers button = mock(HasClickHandlers.class);
...
button.fireEvent(mock(ClickEvent.class));   

Upvotes: 1

Related Questions