使用Mockito的单元测试URL

时间:2018-08-17 00:23:08

标签: java unit-testing mockito

下面的方法检查对指定URL的GET请求是否返回给定的响应。

public class URLHealthCheck extends HealthCheck {
    private URL url;
    private int expectedResponse = 0;

    public URLHealthCheck(String description) {
        setType("urlcheck");
        setDescription(description);
    }

    public Result run() {
        Result result = Result.Fail;
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode == expectedResponse) {
                result = Result.Pass;
            } else {
                setMessage("Expected HTTP code " + expectedResponse + " but received " + responseCode);
            }
        } catch (IOException ex) {
            setMessage(ex.getMessage());
        }
        setResult(result);
        return result;
    }
}

为了测试此方法,我编写了以下测试:

class UrlHealthCheckTest {
    private URLHealthCheck healthCheck;

    @BeforeEach
    void setup() {
        healthCheck = new URLHealthCheck("Test URL");
    }


    @Test
    void testMockUrl() throws IOException {
        URL url = mock(URL.class);
        HttpURLConnection httpURLConnection = mock(HttpURLConnection.class);
        when(httpURLConnection.getResponseCode()).thenReturn(200);
        when(url.openConnection()).thenReturn(httpURLConnection);
        healthCheck.setUrl(url);
        healthCheck.setExpectedResponse(200);
        Result result = healthCheck.run();
        assertTrue(result == Result.Pass);
    }
}

问题在于此单元测试无法完全测试被测方法run(),具体而言,它不会测试这些行

connection.setRequestMethod("GET");
    connection.connect();

最初,我进行了一个测试,该测试使用了现有的网站,例如https://www.google.com,但是它依赖于Internet连接。有什么更好的方法来测试这种方法?

1 个答案:

答案 0 :(得分:0)

您可以验证您的模拟实体是否处于预期状态或执行了某些行为。

Result result = healthCheck.run();

//Verify if `connect` was called exactly once
Mockito.verify(httpURLConnection, Mockito.times(1)).connect(); 

//Verify if a correct Http Method was set
assertEquals("GET", connection.getRequestMethod());