micronaut-test icon indicating copy to clipboard operation
micronaut-test copied to clipboard

@MockBean doesn't work with @Context beans

Open serandel opened this issue 4 years ago • 5 comments

Steps to Reproduce

  1. Annotate a bean as @Context
  2. Use it in a test
  3. Try to mock the bean with @MockBean

Expected Behaviour

The @MockBean method would be invoked and the mocked bean injected in the test and its other beans.

Actual Behaviour

The actual bean is instantiated and the test fails when trying to mock its behaviour with org.mockito.exceptions.misusing.MissingMethodInvocationException.

Environment Information

  • Operating System: macOS Catalina 10.15.7
  • Micronaut Version: 2.1.2
  • JDK Version: 11.0.2

Example Application

https://github.com/serandel/micronauttest-bug

serandel avatar Oct 26 '20 11:10 serandel

I've hit this issue as well with @Context and @Parallel beans. My workaround was to create profile specific beans with the test profile beans as my mocks.

Interested in a better way to workaround this.

albendz avatar Nov 14 '20 02:11 albendz

it works if you make the @MockBean also @Context, eg.

    @MockBean(ContextService.class)
    @Context
    ContextService contextService() {
        def mock = Mock(ContextService.class)
        mock.greet() >> "bar"
        return mock
    }

graemerocher avatar Dec 01 '20 07:12 graemerocher

I didn't think of that! Could we please add the tip to the docs? (I could provide a PR if you wish.) Thanks a lot!

serandel avatar Dec 01 '20 08:12 serandel

PRs welcome!

graemerocher avatar Dec 01 '20 09:12 graemerocher

@graemerocher, is it possible to solve this by adding an alias for DefaultScope or is that a too naive approach? Ideally it would inherit the scope from the original bean definition right?

something like this:

@AliasFor(annotation = DefaultScope.class, member = "value")
Class<? extends Annotation> scope() default Singleton.class;

frehov avatar Jul 01 '22 08:07 frehov