【问题标题】:Mock private static method in final class using PowerMockito使用 PowerMockito 在最终类中模拟私有静态方法
【发布时间】:2015-09-16 05:13:25
【问题描述】:

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

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...);
}

【问题讨论】:

  • 尝试添加PowerMockito.mockStatic(GenerateResponse.class)
  • 仍然调用实际方法
  • @HAR 如果对你有用,请接受我的回答。

标签: java junit mockito powermockito


【解决方案1】:

您应该在whenmethod 中使用参数匹配器。我已经稍微修改了你的代码来运行测试用例。

实际方法

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

【讨论】:

  • 我爱你。你救了我。
猜你喜欢
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-03
相关资源
最近更新 更多