In the following code the beforeEach
method of the ParentConfig
class will get called failing the test.
See https://github.com/biergit/listenerinheritanceissue
@SpringBootTest
@Import({ChildConfig.class})
class ListenerinheritanceissueApplicationTests {
public static int calledByParentConfigBeforeEach = 0;
@Test
void parentConfigBeforeTestMethodShouldNotBeCalled() {
Assertions.assertThat(calledByParentConfigBeforeEach).isEqualTo(0);
}
@Configuration
static class ParentConfig {
@BeforeTestMethod
public void beforeEach(BeforeTestMethodEvent e) {
ListenerinheritanceissueApplicationTests.calledByParentConfigBeforeEach++;
}
}
@Configuration
static class ChildConfig extends ParentConfig {
@Override
public void beforeEach(BeforeTestMethodEvent e) {
// no call to super so there should be no invocation at all
}
}
}
Comment From: rstoyanchev
Thanks for the snippet and I haven't debugged to verify, but given that these are @Configuration
classes within a Test class, is it possible they are each treated as configuration files, i.e. irrespective of @Import
.
Comment From: biergit
Hey @rstoyanchev. You are right. I was wondering how to override an @EventListener
implementation. I had a look at https://stackoverflow.com/a/66706450 and now managed to do what I want like this:
@Configuration
static class ParentConfig {
@EventListener(value = BeforeTestMethodEvent.class,id = "parent")
public void beforeEach(BeforeTestMethodEvent e) {
ListenerinheritanceissueApplicationTests.calledByParentConfigBeforeEach++;
}
}
@Configuration
static class ChildConfig extends ParentConfig {
@Autowired
private ApplicationEventMulticaster eventMulticaster;
@EventListener(ContextRefreshedEvent.class)
void removeParentEventListener(ContextRefreshedEvent e) {
eventMulticaster.removeApplicationListeners(l -> {
return l instanceof SmartApplicationListener
&& ((SmartApplicationListener) l).getListenerId().equals("parent");
});
}
@Override
public void beforeEach(BeforeTestMethodEvent e) {
// no call to super so there should be no invocation at all
}
}