Skip to content

Any way to enable Strict Stubbing when using Mockito.mock() without using @Mock? #2648

@sivaprasadreddy

Description

@sivaprasadreddy

Hi,
I am using mockito-core 4.5.1 and JUnit 5. I can use MockitoExtension and @Mock annotation and by default I get Strict Stubbing behaviour. However, if I use Mockito.Mock(MyClass.class) to create mock it seems Strictness is not enabled. Even if I stub unnecessary methods it is not giving any error.

I know I can work around this by using MockitoExtension to create mocks using @mock, but is there any way to enable Strict Stubbing while using Mockito.mock(MyClass.class);

class ProductServiceTest {

    private ProductRepository productRepository;
    private ProductService productService;

    @BeforeEach
    void setUp() {
        productRepository = Mockito.mock(ProductRepository.class);
        productService = new ProductService(productRepository);
        // this is unnecessary method stubbing but it is not giving any error
        Mockito.when(productRepository.findAllActiveProducts()).thenReturn(List.of());
    }

    @Test
    void shouldReturnOnlyActiveProducts() {
        BDDMockito.given(productRepository.findAll()).willReturn(List.of(p1, p2));
        productService.findAll(); // which calls productRepository.findAll()
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions