Tag: powermock

如何使用JUnit,EasyMock或PowerMock模拟静态最终变量

我想模拟静态最终变量以及使用JUnit,EasyMock或PowerMock模拟i18n类。 我怎么做?

使用PowerMockito模拟私有方法

我正在使用PowerMockito来模拟私有方法调用(privateApi),但它仍然使privateApi调用进而产生另一个thirdPartCall。 当thirdPartyCall抛出exception时,我遇到了问题。 据我所知,如果我在模拟privateApi,它不应该进入方法实现细节并返回模拟响应。 public class MyClient { public void publicApi() { System.out.println(“In publicApi”); int result = 0; try { result = privateApi(“hello”, 1); } catch (Exception e) { Assert.fail(); } System.out.println(“result : “+result); if (result == 20) { throw new RuntimeException(“boom”); } } private int privateApi(String whatever, int num) throws Exception { System.out.println(“In privateAPI”); thirdPartyCall(); […]

在匿名类中测试方法时,如何使用Powermockito来模拟新对象的构造?

我想写一个JUnit测试来validation下面的代码使用BufferedInputStream: public static final FilterFactory BZIP2_FACTORY = new FilterFactory() { public InputStream makeFilter(InputStream in) { // a lot of other code removed for clarity BufferedInputStream buffer = new BufferedInputStream(in); return new CBZip2InputStream(buffer); } }; (FilterFactory是一个接口。) 到目前为止我的测试看起来像这样: @Test public void testBZIP2_FactoryUsesBufferedInputStream() throws Throwable { InputStream in = mock(InputStream.class); BufferedInputStream buffer = mock(BufferedInputStream.class); CBZip2InputStream expected = mock(CBZip2InputStream.class); […]

PowerMock,模拟静态方法,然后在所有其他静态上调用真实方法

我正在设置一个类的静态方法。 我必须在@Before -annotated JUnit设置方法中执行此操作。 我的目标是设置类来调用实际方法, 除了我明确模拟的那些方法。 基本上: @Before public void setupStaticUtil() { PowerMockito.mockStatic(StaticUtilClass.class); when(StaticUtilClass.someStaticMethod(antString())).thenReturn(5); // mock out certain methods… // Now have all OTHER methods call the real implmentation??? How do I do this? } 我StaticUtilClass的问题是,在StaticUtilClass ,方法public static int someStaticMethod(String s)不幸地抛出RuntimeException如果提供了null值)。 因此,我不能简单地将调用实际方法的明显路线作为默认答案,如下所示: @Before public void setupStaticUtil() { PowerMockito.mockStatic(StaticUtilClass.class, CALLS_REAL_METHODS); // Default to calling real static […]

如何使用Mockito / Powermock模拟枚举单例类?

我不确定如何模拟枚举单例类。 public enum SingletonObject{ INSTANCE; private int num; protected setNum(int num) { this.num = num; } public int getNum() { return num; } 我想在上面的例子中存根getNum(),但我无法弄清楚如何模拟实际的SingletonObject类。 我认为使用Powermock准备测试会有所帮助,因为枚举本身就是最终的。 //… rest of test code @Test public void test() { PowerMockito.mock(SingletonObject.class); when(SingletonObject.INSTANCE.getNum()).thenReturn(1); //does not work } 这是使用PowerMockMockito 1.4.10和Mockito 1.8.5。

Powermockito可以在非最终具体类中模拟最终方法吗?

假设我有一个非最终的具体类,其最终方法如下所示。 public class ABC { public final String myMethod(){ return “test test”; } } 是否可以模拟myMethod()在使用Powermockito在junit调用时返回其他内容? 谢谢