Mockito Spy - stub before calling the constructor

前端 未结 3 2133
悲哀的现实
悲哀的现实 2020-12-24 12:40

I\'m trying to spy on an Object and I want to stub a method that is called by the constructor before the constructor calls it.
My class looks like that:

         


        
3条回答
  •  一生所求
    2020-12-24 13:26

    1. Use PowerMock.

    2. After you've imported the libraries, set it up to manipulate the class you want to mock with the instance method that mustn't be called.

    Like so:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({, Myclass.class})
    
    1. Suppress the method at the start of your test.

    Like so:

    suppress(method(Myclass.class, "setup"));
    
    1. Customize the behaviour of your setup() method as desired, in your test.

    Like so:

    doAnswer(new Answer() {
          @Override
          public Void answer(InvocationOnMock invocation) throws Throwable {
               // code here
               return null;
          }
     }).when(Myclass.class, "setup");
    

提交回复
热议问题