2

这是我的代码:

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。

我的测试代码。

@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>

??

4

1 回答 1

4

您需要创建 Jsoup 类的静态模拟。一旦您在测试用例中创建了这样的模拟,您就可以使用它来编写您的期望。

请参阅使用 PowerMockito文档的模拟静态方法。

这里使用 Mockito 和 PowerMockito 的测试用例:

我能够使用 Mockito + Powermockito 模拟执行方法(您同时使用 EasyMock 和 Mockito?)测试用例中的代码如下所示:

@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);
    }
}
于 2013-10-29T13:01:35.640 回答