How to resolve Unneccessary Stubbing exception

前端 未结 13 1456
无人共我
无人共我 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:47

    Looking at a part of your stack trace it looks like you are stubbing the dao.doSearch() elsewhere. More like repeatedly creating the stubs of the same method.

    Following stubbings are unnecessary (click to navigate to relevant line of code):
      1. -> at service.Test.testDoSearch(Test.java:72)
    Please remove unnecessary stubbings or use 'silent' option. More info: javadoc for UnnecessaryStubbingException class.
    

    Consider the below Test Class for example:

    @RunWith(MockitoJUnitRunner.class)
    public class SomeTest {
        @Mock
        Service1 svc1Mock1;
    
        @Mock
        Service2 svc2Mock2;
    
        @InjectMock
        TestClass class;
    
        //Assume you have many dependencies and you want to set up all the stubs 
        //in one place assuming that all your tests need these stubs.
    
        //I know that any initialization code for the test can/should be in a 
        //@Before method. Lets assume there is another method just to create 
        //your stubs.
    
        public void setUpRequiredStubs() {
            when(svc1Mock1.someMethod(any(), any())).thenReturn(something));
            when(svc2Mock2.someOtherMethod(any())).thenReturn(somethingElse);
        }
    
        @Test
        public void methodUnderTest_StateUnderTest_ExpectedBehavior() {
            // You forget that you defined the stub for svcMock1.someMethod or 
            //thought you could redefine it. Well you cannot. That's going to be 
            //a problem and would throw your UnnecessaryStubbingException.
           when(svc1Mock1.someMethod(any(),any())).thenReturn(anyThing);//ERROR!
           setUpRequiredStubs();
        }
    }
    

    I would rather considering refactoring your tests to stub where necessary.

提交回复
热议问题