How to mock a final class with mockito

后端 未结 25 1398
日久生厌
日久生厌 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:37

    I guess you made it final because you want to prevent other classes from extending RainOnTrees. As Effective Java suggests (item 15), there's another way to keep a class close for extension without making it final:

    1. Remove the final keyword;

    2. Make its constructor private. No class will be able to extend it because it won't be able to call the super constructor;

    3. Create a static factory method to instantiate your class.

      // No more final keyword here.
      public class RainOnTrees {
      
          public static RainOnTrees newInstance() {
              return new RainOnTrees();
          }
      
      
          private RainOnTrees() {
              // Private constructor.
          }
      
          public void startRain() {
      
              // some code here
          }
      }
      

    By using this strategy, you'll be able to use Mockito and keep your class closed for extension with little boilerplate code.

提交回复
热议问题