Search code examples
jsfprimefacesjsf-2

How to test a Primefaces GeocodeEvent


I'm using Primefaces 6.1.

I'm working with p:gMap like this

<p:gmap center="#{sellerController.centerGeoMap}"
                                                zoom="13" 
                                                type="MAP" 
                                                style="width:100%;height:300px" 
                                                id="geoGmap" 
                                                widgetVar="geoMap"
                                                binding="#{sellerController.geoMap}"
                                                model="#{sellerController.geoModel}"
                                                >
                                            <p:ajax event="geocode" listener="#{sellerController.onGeocode}" update="@this" />
                                        </p:gmap>

The application is working but I don't know how to test the method called with the ajax event "geocode", because when I try to create an instance of GeocodeEvent an IllegalArgumentException is raised because "source is null"

Here the method to test

public void onGeocode(GeocodeEvent event) {
...
...
}

And here a partial stack trace

java.lang.IllegalArgumentException: null source
    at java.util.EventObject.<init>(EventObject.java:56)
    at javax.faces.event.FacesEvent.<init>(FacesEvent.java:72)
    at javax.faces.event.BehaviorEvent.<init>(BehaviorEvent.java:71)
    at javax.faces.event.AjaxBehaviorEvent.<init>(AjaxBehaviorEvent.java:73)
    at org.primefaces.event.AbstractAjaxBehaviorEvent.<init>(AbstractAjaxBehaviorEvent.java:27)
    at org.primefaces.event.map.GeocodeEvent.<init>(GeocodeEvent.java:30)

How can I test this method? Thank you in advance


Solution

  • Hello guys here the complete example, using Mockito. In fact was pretty obvious... :/

    With Mockito you can mock the two parameters with the following

    UIComponent mockUiComponent = Mockito.mock(UIComponent.class);
    Behavior mockBehavior = Mockito.mock(Behavior.class);
    

    And in my case the rest of the method is like the following:

    sellerController.onGeocode(new GeocodeEvent(mockUiComponent,mockBehavior, "", null));
    //Asserts for the case with null on last parameter
    
    List<GeocodeResult> gResults = new ArrayList<>();
    LatLng expectedLatLng = new LatLng(2d, 3d);
    String expectedTitle = "via dei casari 1";
    gResults.add(new GeocodeResult(expectedTitle, expectedLatLng));
    gResults.add(new GeocodeResult("via dei casari 2",new LatLng(4d, 5d)));
    gResults.add(new GeocodeResult("via dei casari 3",new LatLng(6d, 7d)));
    sellerController.onGeocode(new GeocodeEvent(mockUiComponent,mockBehavior, "", gResults));
    // Asserts for the case with a populated list
    

    Hope to be useful