Java PowerMock外部库
非常简短的问题:如何模拟响应。getContentType()? (使用PowerMock+TestNG)Java PowerMock外部库,java,mocking,mockito,testng,powermock,Java,Mocking,Mockito,Testng,Powermock,非常简短的问题:如何模拟响应。getContentType()? (使用PowerMock+TestNG) 我没有调用任何新的()方法 我试图模拟类,这是其他类的方法执行的结果 被测试的类: class ClassToBeMocked { public String getJsonPage(String jsonUrl) throws IOException { WebClient webClient = new WebClient(BrowserVersion.C
- 我没有调用任何新的()方法
- 我试图模拟类,这是其他类的方法执行的结果
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");
}
}
你不会的。您的问题是,通过将新的WebClient调用放入源代码中,您创建了难以测试的代码。这将导致实现的直接耦合 您应该使用依赖项注入(例如,注入为您创建WebClient对象的工厂)。这样,您就可以使用EasyMock或Mokito等无功耗框架完成所有工作 提示:PowerMock的使用往往表明您的设计可以改进。不知道我在说什么?那就看这些。每一分钟都值得