How to mock a final class with mockito

后端 未结 25 1402
日久生厌
日久生厌 2020-11-22 16:35

I have a final class, something like this:

public final class RainOnTrees{

   public void startRain(){

        // some code here
   }
}

I

25条回答
  •  耶瑟儿~
    2020-11-22 16:58

    Mockito 2 now supports final classes and methods!

    But for now that's an "incubating" feature. It requires some steps to activate it which are described in What's New in Mockito 2:

    Mocking of final classes and methods is an incubating, opt-in feature. It uses a combination of Java agent instrumentation and subclassing in order to enable mockability of these types. As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line:

    mock-maker-inline
    

    After you created this file, Mockito will automatically use this new engine and one can do :

     final class FinalClass {
       final String finalMethod() { return "something"; }
     }
    
     FinalClass concrete = new FinalClass(); 
    
     FinalClass mock = mock(FinalClass.class);
     given(mock.finalMethod()).willReturn("not anymore");
    
     assertThat(mock.finalMethod()).isNotEqualTo(concrete.finalMethod());
    

    In subsequent milestones, the team will bring a programmatic way of using this feature. We will identify and provide support for all unmockable scenarios. Stay tuned and please let us know what you think of this feature!

提交回复
热议问题