How to test method Jsoup.connect (static) using PowerMock?

匿名 (未验证) 提交于 2019-12-03 00:59:01

问题:

This is my code:

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

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.

My code of test.

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

I got

java.lang.Exception: Unexpected exception, expected<com.siteraport.exception.SiteBusinessException> but was<java.lang.IllegalStateException> 

??

回答1:

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.

Please see mock static method using PowerMockito documentation.

Here the Testcase using Mockito and PowerMockito:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!