Skip to content

Document potential need to use Mockito.doXxx() to stub a @MockitoSpyBean #35410

@ofir-popowski

Description

@ofir-popowski

It seems that stubbing a function of a @MockitoSpyBean ends up calling the actual code during the stub. Is that intentional? Should this be documented maybe? I do think it might just be my misunderstanding of mockito spies and/or usage of this annotation, but I found this behavior very surprising

given:

@Service
public class MyService {
    public String mockThis() {
        System.out.println("this should not be printed");
        return "my value";
    }
}

and a simple test:

@SpringBootTest
public class AppTest {
    @MockitoSpyBean private MyService myService;
    
    @Test
    public void checkThis() {
        Mockito.when(myService.mockThis()).thenReturn("stubbed return value");
        System.out.println(myService.mockThis());
        System.out.println(myService.mockThis());
        verify(myService, times(2)).mockThis();
    }
}

The console would show output:

this should not be printed <-- this is printed during `Mockito.when`
stubbed return value
stubbed return value

(I could open a repo with this if required, but it seemed small enough to just post here)

Spring Boot version: 3.5.5

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions