【发布时间】: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