如果我有课
public final class Application {
public static String getName() { return "Bad App"; }
}那么,我如何才能改变行为,让getName返回,比如说,"Good App"?我需要对其进行模拟,以便测试中的类获得预期值。实际上,静态方法会发出一些我想要避免的网络调用。
我不能重写应用程序的代码。
我正在使用Java6、Maven、JUnit和Mockito。
有可能吗?
发布于 2014-12-17 10:23:15
您可以使用powermockito如下所示:
假设这是使用静态方法的类:
public final class MyStaticClass {
public static String helloWorld() {
return "Hello World";
}
}您希望模拟出helloWorld方法,并让它在测试时返回"Hi World“。你可以这样做:
@RunWith(PowerMockRunner.class)
@PrepareForTest({MyStaticClass.class})
public class PowerMockItoTest {
@Test
public void mockStaticClassTest() {
PowerMockito.mockStatic(MyStaticClass.class);
final String mockedResult = "Hi World";
Mockito.when(MyStaticClass.helloWorld()).thenReturn(mockedResult);
Assert.assertEquals(AStaticClass.helloWorld(), mockedResult);
}
}如果您想使用PowerMock,可以这样做:
@RunWith(PowerMockRunner.class)
@PrepareForTest({MyStaticClass.class})
public class PowerMockTest {
@Test
public void testRegisterService() throws Exception {
PowerMock.mockStatic(MyStaticClass.class);
final String mockedResult = "Hi World";
expect(MyStaticClass.helloWorld()).andReturn(mockedResult);
replay(MyStaticClass.class);
Assert.assertEquals(AStaticClass.helloWorld(), mockedResult);
verify(MyStaticClass.class);
}
}https://stackoverflow.com/questions/27523093
复制相似问题