Annotation Type MockBean
-
@Retention(RUNTIME) @Target(FIELD) public @interface MockBeanReplace any guice service with mockito mock in test (using guice module overrides).Important: requires mockito dependency!
Example:
@MockBean Service mock. May be used for static and instance fields.Note: could be used for spy objects creation:
@MockBean Service spy = Mockito.spy(instance). This might be useful in cases when service bound by instance and automatic spy (@SpyBean) can't be used.Mock field might be initialized manually:
@MockBean Service mock = Mockito.mock(Service.class). Manual mocks in instance field must be synchronized with the correct guicey extension declaration (by default, injector created per test class and test instance created per method, so it is impossible to "see" mocks declared in instance fields). Incorrect usage would be immediately reported with error.Mock stubs could be configured in test beforeEach method:
Mockito.when(mock).something().thenReturn("ok").Note that you can use
StubBeanwith manual mock initialization with the almost same result, except it would not be cleared before each test.Mocks reset called after each test method. Could be disabled with
autoReset()Could also be used for spy objects registration of beans bound by instance (!) (so
SpyBeancould not be used):@MockBean Service spy = Mockito.spy(new Service()). Spy should also be used when mock must be created from an abstract class (preserving abstract methods):@MockBean AbstractService mock = Mockito.spy(AbstractService.class).Mockito provide the detailed report of used mock methods and redundant stub definitions. Use
printSummary()to enable this report (printed after each test method).Guicey extension debug (
TestGuiceyApp.debug()) enables mock fields debug: all recognized annotated fields would be printed to console.Limitation: any aop, applied to the original bean, will not work with mock (because guice can't apply aop to instances)! Use
SpyBeaninstead if aop is important. Does not work for HK2 beans.- Since:
- 10.02.2025
-
-
Optional Element Summary
Optional Elements Modifier and Type Optional Element Description booleanautoResetNote: mock could be reset manually withMockito.reset(Object[]).booleanprintSummaryNative mockito mock usage report: shows called methods and stubbed, but not used methods.
-