使用PowerMock和TestNG模拟单个静态方法 [英] Mock a single static method using PowerMock and TestNG

查看:516
本文介绍了使用PowerMock和TestNG模拟单个静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class StaticClass {
  public static String a(){ return "a"; }
  public static String ab(){ return a()+"b"; }
}

我想模拟StaticClass::a,以便它返回"x",并且对StaticClass.ab()的调用导致"xb" ...

I want to mock StaticClass::a so that it returns "x" and the call to StaticClass.ab() results in "xb"...

我发现在PowerMock和TestNG中很难...

I find it very hard in PowerMock and TestNG...

我现在正在测试的确切代码:

the exact code I am testing righ now:

class StaticClass {
    public static String A() {
        System.out.println("Called A");
        throw new IllegalStateException("SHOULD BE MOCKED AWAY!");
    }

    public static String B() {
        System.out.println("Called B");
        return A() + "B";
    }
}

@PrepareForTest({StaticClass.class})
public class StaticClassTest extends PowerMockTestCase {

    @Test
    public void testAB() throws Exception {
        PowerMockito.spy(StaticClass.class);
        BDDMockito.given(StaticClass.A()).willReturn("A");
        assertEquals("AB", StaticClass.B()); // IllegalStateEx is still thrown :-/
    }

}


我对以下内容有Maven依赖项:


I have Maven dependencies on:

<artifactId>powermock-module-testng</artifactId>
and
<artifactId>powermock-api-mockito</artifactId>

推荐答案

为什么不尝试:

PowerMockito.mockStatic(StaticClass.class);
Mockito.when(StaticClass.a()).thenReturn("x");
Mockito.when(StaticClass.ab()).thenCallRealMethod();

这篇关于使用PowerMock和TestNG模拟单个静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆