下面的代码testMethod
仅更改静态方法的行为,而不会影响其他静态方法.
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PrepareForTest({Foo.class }) public class Snipets { @Test public void hoge() throws Exception { PowerMockito.spy(Foo.class); PowerMockito.when(Foo.class, "testMethod").thenReturn("dummy"); String actual = Foo.testMethod(); assertEquals("dummy", actual); } }
Foo.java
public class Foo { public static String testMethod() { return "foo"; } }
资料来源:https://gist.github.com/mid0111/8859159
下面的代码testMethod
仅更改静态方法的行为,而不会影响其他静态方法.
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PrepareForTest({Foo.class }) public class Snipets { @Test public void hoge() throws Exception { PowerMockito.spy(Foo.class); PowerMockito.when(Foo.class, "testMethod").thenReturn("dummy"); String actual = Foo.testMethod(); assertEquals("dummy", actual); } }
Foo.java
public class Foo { public static String testMethod() { return "foo"; } }
资料来源:https://gist.github.com/mid0111/8859159