Mějme následující třídu, kterou chceme otestovat:
public class Foo {
public static String BAR = "bar";
public Foo() {
}
public static int fooMethod(final String fooParameter) {
try {
if (!BAR.isEmpty()) {
return ((BAR + fooParameter).length());
} else {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException e) {
throw new RuntimeException();
}
}
}
A příslušný unit test:
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import org.junit.Test;
public class FooTest {
@Test(expected = RuntimeException.class)
public void testFooMethodEmptyStaticFinalField() throws Exception {
// set public static field BAR to empty string to be able test
Field staticField = Foo.class.getDeclaredField("BAR");
staticField.setAccessible(true);
Field staticFieldModifiers = staticField.getClass().getDeclaredField("modifiers");
staticFieldModifiers.setAccessible(true);
staticFieldModifiers.setInt(staticField, staticField.getModifiers() & ~Modifier.FINAL);
staticField.set(null, "");
Foo.fooMethod("any vaue");
}
}
Původní třídu však musíme modifikovat následujícím způsobem:
public class Foo {
public static String BAR = new String("bar");
public Foo() {
}
public static int fooMethod(final String fooParameter) {
try {
if (!BAR.isEmpty()) {
return ((BAR + fooParameter).length());
} else {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException e) {
throw new RuntimeException();
}
}
}
A voila...
Žádné komentáře:
Okomentovat