带导入的StaticServiceTest.java:
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ StaticService.class })
public class StaticServiceTest {
@Test(expected = IllegalArgumentException.class)
public void testMockStatic1() throws Exception {
/* Setup */
String sayString = "hello";
PowerMockito.mockStatic(StaticService.class);
/* Mocks */
PowerMockito.doThrow(new IllegalArgumentException("Mockerror")).when(
StaticService.class, "say", Matchers.eq(sayString));
/* Test */
StaticService.say(sayString);
/* Asserts */
fail("Expected exception not thrown.");
}
@Test(expected = IllegalArgumentException.class)
public void testMockStatic2() throws Exception {
/* Setup */
String sayString = "hello";
PowerMockito.mockStatic(StaticService.class);
/* Mocks */
PowerMockito.doThrow(new IllegalArgumentException("Mockerror")).when(
StaticService.class);
StaticService.say(Matchers.eq(sayString));
/* Test */
StaticService.say(sayString);
/* Asserts */
fail("Expected exception not thrown.");
}
}
静态服务.java
public class StaticService {
public static void say(String arg) {
System.out.println("Say: " + arg);
}
}
测试通过: