Mocking Static Blocks in Java

后端 未结 10 2055
南方客
南方客 2021-01-30 11:00

My motto for Java is \"just because Java has static blocks, it doesn\'t mean that you should be using them.\" Jokes aside, there are a lot of tricks in Java that make testing a

10条回答
  •  灰色年华
    2021-01-30 11:25

    You could write your test code in Groovy and easily mock the static method using metaprogramming.

    Math.metaClass.'static'.max = { int a, int b -> 
        a + b
    }
    
    Math.max 1, 2
    

    If you can't use Groovy, you will really need to refactoring the code (maybe to inject something like a initializator).

    Kind Regards

提交回复
热议问题