How to mock a final class with mockito

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

    You cannot mock a final class with Mockito, as you can't do it by yourself.

    What I do, is to create a non-final class to wrap the final class and use as delegate. An example of this is TwitterFactory class, and this is my mockable class:

    public class TwitterFactory {
    
        private final twitter4j.TwitterFactory factory;
    
        public TwitterFactory() {
            factory = new twitter4j.TwitterFactory();
        }
    
        public Twitter getInstance(User user) {
            return factory.getInstance(accessToken(user));
        }
    
        private AccessToken accessToken(User user) {
            return new AccessToken(user.getAccessToken(), user.getAccessTokenSecret());
        }
    
        public Twitter getInstance() {
            return factory.getInstance();
        }
    }
    

    The disadvantage is that there is a lot of boilerplate code; the advantage is that you can add some methods that may relate to your application business (like the getInstance that is taking a user instead of an accessToken, in the above case).

    In your case I would create a non-final RainOnTrees class that delegate to the final class. Or, if you can make it non-final, it would be better.

提交回复
热议问题