How to mock a final class with mockito

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

    Please look at JMockit. It has extensive documentation with a lot of examples. Here you have an example solution of your problem (to simplify I've added constructor to Seasons to inject mocked RainOnTrees instance):

    package jmockitexample;
    
    import mockit.Mocked;
    import mockit.Verifications;
    import mockit.integration.junit4.JMockit;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    
    @RunWith(JMockit.class)
    public class SeasonsTest {
    
        @Test
        public void shouldStartRain(@Mocked final RainOnTrees rain) {
            Seasons seasons = new Seasons(rain);
    
            seasons.findSeasonAndRain();
    
            new Verifications() {{
                rain.startRain();
            }};
        }
    
        public final class RainOnTrees {
            public void startRain() {
                // some code here
            }
    
        }
    
        public class Seasons {
    
            private final RainOnTrees rain;
    
            public Seasons(RainOnTrees rain) {
                this.rain = rain;
            }
    
            public void findSeasonAndRain() {
                rain.startRain();
            }
    
        }
    }
    

提交回复
热议问题