1. 加入依赖包(maven)
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.4.10</version>
<scope>test</scope>
</dependency>
2. 测试
class MyStringUtil {
public static String uppercase(String s) {
return s.toUpperCase();
}
}
@RunWith(PowerMockRunner.class) // 1
@PrepareForTest({ MyStringUtil.class }) // 2
public class HelloTest {
@Before
public void before() {
PowerMockito.mockStatic(MyStringUtil.class); // 3
}
@Test
public void test() throws IOException {
PowerMockito.when(MyStringUtil.uppercase("abc")).thenReturn("ABC"); // 4
assertEquals("ABC", MyStringUtil.uppercase("abc")); // 5
}
}