Skip to content

@MockitoBean does not get reset in inherited @Nested tests #34906

@stan-borissov

Description

@stan-borissov

In the snippet below, the ServiceB @MockitoBean is not reset between firstNestedTest() and secondNestedTest(), but it should be. This causes secondNestedTest to fail on verify(serviceB).bar();, as there are 2 invocations instead of just the expected 1.

Note that the @Import(ServiceC.class) on ChildTests is not required for the test as such, but causes (by some mysterious means) the failure to reset ServiceB, as removing the @Import will make the test pass.

Spring Boot version is 3.4.5.

This issue may be related to spring-projects/spring-boot#12470.

Services

@Component
public class ServiceA {
    @Autowired
    public ServiceB serviceB;

    public void foo() {
        serviceB.bar();
    }
}
@Component
public class ServiceB {
    public void bar() {
    }
}
@Component
public class ServiceC {
}

Test

@SpringBootTest
public abstract class ParentTests {

    @MockBean
    ServiceB serviceB;
    @Autowired
    ServiceA serviceA;

    @Nested
    class NestedTest {

        @Test
        void firstNestedTest() {
            serviceA.foo();
            verify(serviceB).bar();
        }

        @Test
        void secondNestedTest() {
            serviceA.foo();
            verify(serviceB).bar();
        }
    }
}
@Import(ServiceC.class)
public class ChildTests extends ParentTests {
}

Metadata

Metadata

Assignees

Labels

in: testIssues in the test modulestatus: duplicateA duplicate of another issue

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions