unit testing - Mocking Static Blocks in Java -
my motto java "just because java has static blocks, doesn't mean should using them." jokes aside, there lot of tricks in java make testing nightmare. 2 of hate anonymous classes , static blocks. have lot of legacy code make use of static blocks , these 1 of annoying points in our push in writing unit tests. our goal able write unit tests classes depend on static initialization minimal code changes.
so far suggestion colleagues move body of static block private static method , call staticinit
. method can called within static block. unit testing class depends on class mock staticinit
jmockit not anything. let's see in example.
public class classwithstaticinit { static { system.out.println("static initializer."); } }
will changed to
public class classwithstaticinit { static { staticinit(); } private static void staticinit() { system.out.println("static initialized."); } }
so can following in junit.
public class dependentclasstest { public static class mockclasswithstaticinit { public static void staticinit() { } } @beforeclass public static void setupbeforeclass() { mockit.redefinemethods(classwithstaticinit.class, mockclasswithstaticinit.class); } }
however solution comes own problems. can't run dependentclasstest
, classwithstaticinittest
on same jvm since want static block run classwithstaticinittest
.
what way of accomplishing task? or better, non-jmockit based solutions think work cleaner?
when run problem, same thing describe, except make static method protected can invoke manually. on top of this, make sure method can invoked multiple times without problems (otherwise no better static initializer far tests go).
this works reasonably well, , can test static initializer method expect/want do. easiest have static initialization code, , isn't worth build overly complex system replace it.
when use mechanism, make sure document protected method exposed testing purposes, hopes won't used other developers. of course may not viable solution, example if class' interface externally visible (either sub-component of kind other teams, or public framework). simple solution problem though, , doesn't require third party library set (which like).
Comments
Post a Comment