mocking GWT EventBus with mockito

谁说胖子不能爱 提交于 2019-12-08 02:03:36

问题


I have some problems spying on a real SimpleEventBus implementation of EventBus: I have an activity which is also a handler for a specific event. This event is fired by a service.

The code:

    @Mock private AssetCellList view;
    @Mock private AcceptsOneWidget panel;
    @Mock private SelectionModel<Asset> selectionModel;
    @Mock private HasData<Asset> cellList;
    @Mock private AssetService service;
    @Mock private Asset asset;
    @Mock private List<Asset> list;
    @Mock private AssetListDTOClientImpl assetDTO;
    @Mock private AssetEvent event;


    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test 
    public void test(){


        /*Some stubbing*/
        when(view.getSelectionModel()).thenReturn(selectionModel);
        when(view.getList()).thenReturn(cellList);
        when(assetDTO.getAssetList()).thenReturn(list);
        when(assetDTO.getAssetList().get(anyInt())).thenReturn(asset);
        when(event.getAssetDTO()).thenReturn(assetDTO);


        /*Creatin the Real EventBus*/
        EventBus eventBus = new SimpleEventBus();

        /*Creating the activity */
        AssetListActivity activity = new AssetListActivity(eventBus, 
                view,
                service);

        /*Spying the eventBus*/
        EventBus eventBusSpy = spy(eventBus);
        /*Spying the activity*/
        AssetListActivity activitySpy = spy(activity);


        /*Starting the activity*/
        activity.start(panel);

        /*verifying the service call -> OK */
        verify(service, times(1)).getAssets(anyInt());

        /*Simulating the service which eventually fires an event*/
        eventBus.fireEvent(event);

        /*verifying that the eventBus really fires the event --> NO OK*/
        verify(eventBusSpy, times(1)).addHandler( eq( AssetEvent.TYPE ),                      isA(AssetEventHandler.class));

        /*later verifiction*/
        verify(activitySpy).onAssetsReceived(event);

    }

The error trace is in th eventBusSpy verification and says:

Wanted but not invoked:
simpleEventBus.addHandler(
    Event type,
    isA(cat.ccma.testproject.client.events.AssetEventHandler)
);
-> at cat.ccma.testproject.client.AssetListTest.test(AssetListTest.java:87)
Actually, there were zero interactions with this mock.

Thank You.


回答1:


Shouldn't you pass the spied instance to your activity, instead of spying it afterwards?

Note you can also use a com.google.gwt.event.shared.testing.CountingEventBus which is a simple EventBus (uses new SimpleEventBus unless you pass an EventBus instance to be wrapped) with the addition of a getCount(GwtEvent.Type) method. You'd then do an assertEquals(1, countingEventBus.getCount(AssetEvent.TYPE));



来源:https://stackoverflow.com/questions/4431131/mocking-gwt-eventbus-with-mockito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!