How to mock a final class with mockito

后端 未结 25 1131
日久生厌
日久生厌 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 17:01

    Actually there is one way, which I use for spying. It would work for you only if two preconditions are satisfied:

    1. You use some kind of DI to inject an instance of final class
    2. Final class implements an interface

    Please recall Item 16 from Effective Java. You may create a wrapper (not final) and forward all call to the instance of final class:

    public final class RainOnTrees implement IRainOnTrees {
        @Override public void startRain() { // some code here }
    }
    
    public class RainOnTreesWrapper implement IRainOnTrees {
        private IRainOnTrees delegate;
        public RainOnTreesWrapper(IRainOnTrees delegate) {this.delegate = delegate;}
        @Override public void startRain() { delegate.startRain(); }
    }
    

    Now not only can you mock your final class but also spy on it:

    public class Seasons{
        RainOnTrees rain;
        public Seasons(IRainOnTrees rain) { this.rain = rain; };
        public void findSeasonAndRain(){
            rain.startRain();
       }
    }
    
    IRainOnTrees rain = spy(new RainOnTreesWrapper(new RainOnTrees()) // or mock(IRainOnTrees.class)
    doNothing().when(rain).startRain();
    new Seasons(rain).findSeasonAndRain();
    
    0 讨论(0)
提交回复
热议问题