繁体   English   中英

使用PowerMockito模拟最终类中的私有静态方法

[英]Mock private static method in final class using PowerMockito

我有一个带有私有静态方法的final类,它在另一个静态方法中调用

public final class GenerateResponse{
      private static Map<String, String> getErrorDetails(JSONObject jsonObject) {
         // implementation
      }

      public static String method1(params...){
         Map<String, String> map = getErrorDetails(new JsonObject());

         // implementation
      }
}

我需要模拟私有静态方法调用getErrorDetails() ,但我的测试是调用实际方法。 这是我的代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest(GenerateResponse.class)
public class GenerateResponseTest{

@Test
public void testFrameQtcErrorResponse() throws Exception {
    Map<String, String> errorDtls = new HashMap<String, String>();

    PowerMockito.spy(GenerateResponse.class);
    PowerMockito.doReturn(errorDtls).when(GenerateResponse.class, "getErrorDetails", JSONObject.class);
    String response = GenerateResponse.method1(params...);
}

您应该在when方法中使用参数匹配器。 我已经修改了你的代码以运行测试用例。

实际方法

public final class GenerateResponse{

    private static Map<String, String> getErrorDetails(JSONObject jsonObject) {
       return null;
    }

    public static String method1() {
    Map<String, String> map = getErrorDetails(new JSONObject());
    return map.get("abc");
    }
}

测试方法

@RunWith(PowerMockRunner.class)
@PrepareForTest(GenerateResponse.class)
public class GenerateResponseTest {

@Test
public void testFrameQtcErrorResponse() throws Exception {
    Map<String, String> errorDtls = new HashMap<String, String>();
    errorDtls.put("abc", "alphabets");

    PowerMockito.mockStatic(GenerateResponse.class, Mockito.CALLS_REAL_METHODS);

    PowerMockito.doReturn(errorDtls).when(GenerateResponse.class,
            "getErrorDetails", Matchers.any(JSONObject.class));

    String response = GenerateResponse.method1();

    System.out.println("response =" + response);

   }

 }

产量

response =alphabets

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM