Class MocksHook

  • All Implemented Interfaces:
    GuiceyConfigurationHook

    public class MocksHook
    extends java.lang.Object
    implements GuiceyConfigurationHook
    Replace any guice service with mockito mock in test (using guice module overrides).

    Important: requires mockito dependency!

    Usage example:

    
      MocksHook hook = new MocksHook();
      Service mock = hook.mock(Service.class);
      when(mock.foo()).thenReturn(..)
     

    Could also be used for spy objects registration of beans bound by instance (!) (so SpiesHook could not be used): Service spy = hook.mock(Service.class, Mockito.spy(new Service())). Spy should also be used when mock must be created from an abstract class (preserving abstract methods): AbstractService mock = hook.mock(AbstractService.class, Mockito.spy(AbstractService.class)).

    Limitation: any aop, applied to the original bean, will not work with mock (because guice can't apply aop to instances)! Use SpiesHook instead if aop is important. Does not work for HK2 beans.

    Since:
    29.04.2025
    • Constructor Summary

      Constructors 
      Constructor Description
      MocksHook()  
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void configure​(GuiceBundle.Builder builder)
      Configuration is applied just after manual configuration (through bundle's builder in application class).
      <T> T getMock​(java.lang.Class<T> type)  
      <T> T mock​(java.lang.Class<T> type)
      Override gucie bean with a mock instance.
      <T> T mock​(java.lang.Class<T> type, T mock)
      Override guice bean with a user-provided mock instance.
      void resetMocks()
      Reset all registered mocks.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • MocksHook

        public MocksHook()
    • Method Detail

      • mock

        public <T> T mock​(java.lang.Class<T> type)
        Override gucie bean with a mock instance.
        Type Parameters:
        T - bean type
        Parameters:
        type - bean type
        Returns:
        mock instance
      • mock

        public <T> T mock​(java.lang.Class<T> type,
                          T mock)
        Override guice bean with a user-provided mock instance.
        Type Parameters:
        T - bean type
        Parameters:
        type - bean type
        mock - mock instance
        Returns:
        passed mock instance
      • getMock

        public <T> T getMock​(java.lang.Class<T> type)
        Type Parameters:
        T - bean type
        Parameters:
        type - bean type
        Returns:
        mock instance registered for bean type
        Throws:
        java.lang.IllegalStateException - if mock for type is not registered
      • resetMocks

        public void resetMocks()
        Reset all registered mocks.