How to mock static method without powermock

前端 未结 4 1676
野趣味
野趣味 2020-12-09 01:53

Is there any way we can mock the static util method while testing in JUnit?

I know Powermock can mock static calls, but I don\'t want to use Powermock.

Are

4条回答
  •  误落风尘
    2020-12-09 02:17

    I've had a lot of luck with doing something similar to what Maciej suggested in his answer above. In Java8 I like to wrap those static methods with functional interfaces to make them more straightforward to inject or mock. For example:

    public class MyClass {
        private MyStaticWrapper staticWrapper;
    
        public MyClass(final MyStaticWrapper staticWrapper) {
            this.staticWrapper = staticWrapper;
        }
    
        public void main() {
            ...
            staticWrapper.doSomething();
            ...    
        }
    }    
    
    public interface MyStaticWrapper {
        default void doSomething() {
          Util.annoyingUntestableStaticFunction();
        }
    }
    

提交回复
热议问题