TL;DR
@RunWith(PowerMockRunner.class)
--@ PrepareForTest ({getestete Klasse})
@PowerMockRunnerDelegate(Parameterized.class)
--@ PowerMockRunnerDelegate (JUnit4.class)
ist nicht erforderlich--static initializer Ich wollte einen Test der auszuführenden Verarbeitung schreiben
public class StaticClass {
public static String MESSAGE;
static {
int i = new Random().nextInt();
if (0 <= i && i <= 10) {
MESSAGE = "Parameter is inside of range, 0 to 10.";
} else {
MESSAGE = "Nmm...?";
method();
}
}
private static void method() {
// to do any action
}
}
@RunWith(Enclosed.class)
public class StaticClassTest {
@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticClass.class})
@PowerMockRunnerDelegate(Parameterized.class)
public static class ParameterizeTest {
@Parameterized.Parameter
public Integer parameter;
@Parameterized.Parameters(name = "parameter is {0}")
public static Object[][] parameterSupplier() {
return new Object[][]{
{0},
{1},
{2},
{3},
{4},
{5},
{6},
{7},
{8},
{9},
{10}
};
}
@Test
public void test() throws Exception {
// given
Random random = PowerMockito.mock(Random.class);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
PowerMockito.when(random.nextInt()).thenReturn(parameter);
// expect
assertEquals("Parameter is inside of range, 0 to 10.",
Whitebox.getInternalState(StaticClass.class, "MESSAGE"));
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticClass.class})
public static class NormalTest {
@Test
public void test() throws Exception {
// given
Random random = PowerMockito.mock(Random.class);
PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(random);
PowerMockito.when(random.nextInt()).thenReturn(99);
// expect
assertEquals("Nmm...?",
Whitebox.getInternalState(StaticClass.class, "MESSAGE"));
}
}
}
http://tomoyamkung.net/2013/08/28/java-junit4-enclosed/ https://stackoverflow.com/questions/28027445/powermock-access-private-members
Recommended Posts