这是我的代码:
public void analyze(String url) throws SiteBusinessException { Document doc = null; Response response = null; try { response = Jsoup.connect(url).execute(); doc = Jsoup.connect(url).get(); } catch (IOException e) { LOGGER.warn("Cannot analyze site [url={}, statusCode={}, statusMessage={} ]", new Object[] {url, response.statusCode(), response.statusMessage()}); throw new SiteBusinessException(response.statusMessage(), String.valueOf(response.statusCode())); } }如何使用PowerMock测试此方法?我想编写测试以检查在调用.execute()时是否抛出IOException并捕获并随后抛出SiteBusinessException.
How can I test this method using PowerMock? I want to write test to check that when invoke .execute() then throw IOException and it catch then throw SiteBusinessException.
我的测试代码.
@RunWith(PowerMockRunner.class) @PrepareForTest({Jsoup.class}) Test(expected = SiteBusinessException.class) public void shouldThrowIOException() throws Exception { Connection connection = PowerMockito.mock(Connection.class); Response response = PowerMockito.mock(Response.class); PowerMockito.when(connection.execute()).thenReturn(response); PowerMockito.mockStatic(Jsoup.class); expect(Jsoup.connect(SITE_URL)).andReturn(connection); replay(Jsoup.class); PowerMockito.when(Jsoup.connect(SITE_URL).execute()).thenThrow(new IOException()); AnalyzerService sut = new AnalyzerServiceImpl(); sut.analyzeSite(SITE_URL); }我知道了
java.lang.Exception: Unexpected exception, expected<com.siteraport.exception.SiteBusinessException> but was<java.lang.IllegalStateException>??
推荐答案您需要创建Jsoup类的静态模拟.一旦在测试用例中创建了这样的模拟,就可以使用它来编写期望值.
You need to create a static mock of the Jsoup class. Once you have created such a mock in your test case, you can code your expectations using it.
请参阅使用PowerMockito模拟静态方法文档.
在这里使用Mockito和PowerMockito测试用例:
Here the Testcase using Mockito and PowerMockito:
我能够使用Mockito + Powermockito模拟执行方法(您同时使用EasyMock和Mockito吗?)测试用例中的代码如下:
I was able to mock the execute method using Mockito + Powermockito (you are using both EasyMock and Mockito?) The code in the test case looks as below:
@RunWith(PowerMockRunner.class) @PrepareForTest({Jsoup.class}) public class MyClassTest { @Test(expected = SiteBusinessException.class) public void shouldThrowIOException() throws Exception { String SITE_URL = "some_url_string"; Connection connection = Mockito.mock(Connection.class); Mockito.when(connection.execute()).thenThrow(new IOException("test")); PowerMockito.mockStatic(Jsoup.class); PowerMockito.when(Jsoup.connect(Mockito.anyString())). thenReturn(connection); AnalyzerService sut = new AnalyzerService(); sut.analyze(SITE_URL); } }更多推荐
如何使用PowerMock测试方法Jsoup.connect(静态)?
发布评论