Skip to content

ApplicationContext reloaded when @MockitoBean and @ContextHierarchy are mixed on single class #33293

Closed as not planned
@jonenst

Description

@jonenst

Hi,
attached is a testcase showing a testcontest that is wrongly reloaded when using @MockBean in conjunction with using @ContextHierarchy in single class mode.

The testcase is in the attached zip, in the "notworking" folder. the "working" folder is present only for comparison to illustrate the bug.

run $ mvn package at the root to run the testcases.
mockbean-hiearchy-singleclass-bug.zip

[INFO] aggregator 0.0.1-SNAPSHOT .......................... SUCCESS [  0.559 s]
[INFO] working ............................................ SUCCESS [  2.830 s]
[INFO] notworking 0.0.1-SNAPSHOT .......................... FAILURE [  1.718 s]

the testcase shows that a context that should be cached is instead reloaded when multiple classes using the same context as the parent of a contexthiearchy, and using mockbean on a bean in a child context (so the parent should still be reusable):

DOESN'T WORK

@ContextHierarchy({
    @ContextConfiguration(classes = ErrorIfContextReloaded.class),
    @ContextConfiguration(classes = DefaultFooService.class),
})
@ExtendWith(SpringExtension.class)
class Demo1ApplicationTests {

    @MockBean
    DefaultFooService fooService;

}
@ContextHierarchy({
    @ContextConfiguration(classes = ErrorIfContextReloaded.class),
    @ContextConfiguration(classes = DefaultFooService2.class),
})
@ExtendWith(SpringExtension.class)
class Demo2ApplicationTests {

    @MockBean
    DefaultFooService2 fooService;

}

The bug does not happen when using @ContextHiearchy with subclassing:
WORKS

@ContextHierarchy({
    @ContextConfiguration(classes = ErrorIfContextReloaded.class),
})
@ExtendWith(SpringExtension.class)
class Demo1ApplicationTests {
}

@ContextHierarchy({ @ContextConfiguration(classes = DefaultFooService.class), })
class Demo1ApplicationChildTests extends Demo1ApplicationTests {
    @MockBean
    DefaultFooService fooService;
}
@ContextHierarchy({
    @ContextConfiguration(classes = ErrorIfContextReloaded.class),
})
@ExtendWith(SpringExtension.class)
class Demo2ApplicationTests {
}

@ContextHierarchy({ @ContextConfiguration(classes = DefaultFooService2.class), })
class Demo2ApplicationChildTests extends Demo2ApplicationTests {
    @MockBean
    DefaultFooService2 fooService;
}

This prevents reliable context caching, useful for example when expensive beans (like test databases and databases connections) are created only once in a parent context for every test classes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: testIssues in the test modulestatus: supersededAn issue that has been superseded by anothertype: bugA general bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions