Is it possible to do strict mocks with Mockito?

后端 未结 6 1386
傲寒
傲寒 2021-02-12 20:13

I\'d like to use strict mocks, at least when developing for the first time some tests against old code, so any methods invoked on my mock will throw an exception if I didn\'t sp

6条回答
  •  执笔经年
    2021-02-12 20:46

    Add this @Rule to your test class as a public field:

    @RunWith(JUnitParamsRunner.class)
    public class MyClassTests {
    
        @Rule
        public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
    
        @Test
        ....
    }
    

    This value was added to Mockito in version 2.3.0

    From the documentation:

    Ensures clean tests, reduces test code duplication, improves debuggability. Offers best combination of flexibility and productivity. Highly recommended. Planned as default for Mockito v3. Adds following behavior:

    • Improved productivity: the test fails early when code under test invokes stubbed method with different arguments (see PotentialStubbingProblem).
    • Cleaner tests without unnecessary stubbings: the test fails when unused stubs are present (see UnnecessaryStubbingException).
    • Cleaner, more DRY tests ("Don't Repeat Yourself"): If you use Mockito.verifyNoMoreInteractions(Object...) you no longer need to explicitly verify stubbed invocations. They are automatically verified for you.

提交回复
热议问题