How to resolve Unneccessary Stubbing exception

前端 未结 13 1453
无人共我
无人共我 2020-12-24 03:57

My Code is as below,

@RunWith(MockitoJUnitRunner.class)
public class MyClass {

    private static final String code =\"Test\";

    @Mock
     private MyCl         


        
13条回答
  •  清酒与你
    2020-12-24 04:43

    At first you should check your test logic. Usually there are 3 cases. First, you are mocking wrong method (you made a typo or someone changed tested code so that mocked method is no longer used). Second, your test is failing before this method is called. Third, you logic falls in wrong if/switch branch somewhere in the code so that mocked method is no called.

    If this is first case you always want to change mocked method for the one used in the code. With second and the third it depends. Usually you should just delete this mock if it has no use. But sometimes there are certain cases in parametrized tests, which should take this different path or fail earlier. Then you can split this test into two or more separate ones but that's not always good looking. 3 test methods with possibly 3 arguments providers can make you test look unreadable. In that case for JUnit 4 you silent this exception with either

    @RunWith(MockitoJUnitRunner.Silent.class) 
    

    annotation or if you are using rule approach

    @Rule
    public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.LENIENT);
    

    or (the same behaviour)

    @Rule
    public MockitoRule rule = MockitoJUnit.rule().silent();
    

    For JUnit 5 tests you can silent this exception using annotation provided in mockito-junit-jupiter package.

    @ExtendWith(MockitoExtension.class)
    @MockitoSettings(strictness = Strictness.LENIENT)
    class JUnit5MockitoTest {
    }
    

提交回复
热议问题