【问题标题】:PowerMock mock external libraryPowerMock 模拟外部库
【发布时间】:2016-09-09 22:12:19
【问题描述】:

非常简短的问题:我如何模拟 response.getContentType() ? (使用 PowerMock + TestNG)

  • 我没有调用任何 new() 方法。
  • 我正在尝试模拟类,这是某个其他类的方法执行的结果。

被测类:

class ClassToBeMocked {

    public String getJsonPage(String jsonUrl) throws IOException {
        WebClient webClient = new WebClient(BrowserVersion.CHROME);

        final Page page = webClient.getPage(jsonUrl);
        final WebResponse response = page.getWebResponse();
        final String cType = response.getContentType();

        if (cType.equals("application/json") || cType.equals("application/hal+json")) {
            return response.getContentAsString();
        }

        throw new IllegalArgumentException("Unexpected response type " + response.getContentType());
    }
}

自我测试

@PrepareForTest( { WebResponse.class, ClassToBeMocked.class})
@PowerMockIgnore("javax.net.ssl.*")
public class UrlPullerTest extends PowerMockTestCase {

    @Test
    public void testGetPage() throws Exception {
        WebResponse mockwebResposne = PowerMockito.mock(WebResponse.class);
        PowerMockito.when(mockwebResposne.getContentType()).thenReturn("wrongType");

        ClassToBeMocked classToBeMocked = new ClassToBeMocked();
        classToBeMocked.getJsonPage("http://google.com");
    }
}

【问题讨论】:

    标签: java mocking mockito testng powermock


    【解决方案1】:

    你不会的。您的问题是您通过将 new WebClient 调用放入源代码中创建了 难以测试 代码。这导致实现的直接耦合。

    您应该改用依赖注入(例如注入为您创建 WebClient 对象的工厂)。这样做,您可以使用 EasyMock 或 Mokito 等无动力框架完成所有工作。

    提示:很多时候,PowerMock 的使用表明您的设计可以改进。不知道我在说什么?然后观看这些videos。每一个都值得每一分钟!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多