jakarta-eeglassfishpayarahk2

How can I inject CDI event with HK2 in JUnit Test?


I would like to test my Jakarta application (Payara) with simply JUnit Test (without arquillian, without MicroShed).

I use ServiceLocator from Hk2 to inject service and its work well for my JPA entity and Service.

private static ServiceLocator serviceLocator;

@BeforeAll
public static void setUpBeforeClass() {
    serviceLocator = ServiceLocatorUtilities.createAndPopulateServiceLocator();
    ServiceLocatorUtilities.addClasses(
            serviceLocator,
            EntityManagerHK2Factory.class,
            ProducerUtils.class,
            FishService.class,
            ShopRepository.class,
            Family.class, Fish.class, FishStockKey.class, Shop.class, Stock.class, WaterType.class);
}

@Test
public void it_should_sell_fish() {
    //GIVEN
    FishService fishService = serviceLocator.getService(FishService.class);
    String shopName = "Magic Fish";
    String fishName = "Scalaire";
    int quantity = 3;
    //WHEN
    float bill = fishService.sell(shopName, fishName, quantity);
    //THEN
    assertThat(bill, is(54f));
}

But I have some issues since I had include CDI event inside my FishService.

@Inject
private Event<StockEvent> stockEvent;

And then I fire an event.

When I launch the test serviceLocator does not manage to create the FishService and I get the following error:

A MultiException has 3 exceptions.  They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=Event<StockEvent>,parent=FishService,qualifiers={},position=-1,optional=false,self=false,unqualified=null,976949492)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.meynier.jakarta.service.FishService errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on com.meynier.jakarta.service.FishService

In this test class I don't want to test the event CDI feature.

How can I use Hk2 to inject the CDI event service ? (My code is host in this github account)


Solution

  • You can use Mockito to mock the Event and then bind the mock with an AbstractBinder and add that to the ServiceLocator. Here's a complete test

    import javax.inject.Inject;
    
    import org.glassfish.hk2.api.ServiceLocator;
    import org.glassfish.hk2.api.TypeLiteral;
    import org.glassfish.hk2.utilities.Binder;
    import org.glassfish.hk2.utilities.ServiceLocatorUtilities;
    import org.glassfish.hk2.utilities.binding.AbstractBinder;
    import org.junit.BeforeClass;
    import org.junit.Test;
    
    import static org.assertj.core.api.Assertions.assertThat;
    import static org.mockito.Mockito.mock;
    import static org.mockito.Mockito.when;
    
    public class Hk2CdiInjectTest {
    
        public interface Event<T> {
            T get();
        }
    
        public interface StockEvent {
            String getStock();
        }
    
        public static class Service {
    
            @Inject
            private Event<StockEvent> event;
    
            public String getStock() {
                return event.get().getStock();
            }
        }
    
        private static ServiceLocator locator;
    
        @BeforeClass
        public static void setUpBeforeClass() {
            locator = ServiceLocatorUtilities.createAndPopulateServiceLocator();
            ServiceLocatorUtilities.addClasses(locator, Service.class);
    
            final Event<StockEvent> event = (Event<StockEvent>) mock(Event.class);
            final StockEvent stockEvent = mock(StockEvent.class);
            when(stockEvent.getStock()).thenReturn("GOOGL UP!");
            when(event.get()).thenReturn(stockEvent);
            Binder eventBinder = new AbstractBinder() {
                @Override
                public void configure() {
                    bind(event).to(new TypeLiteral<Event<StockEvent>>() {});
                }
            };
            ServiceLocatorUtilities.bind(locator, eventBinder);
        }
    
        @Test
        public void testIt() {
            Service service = locator.getService(Service.class);
    
            assertThat(service.getStock()).isEqualTo("GOOGL UP!");
        }
    }