首页 > 解决方案 > 带有 Mockito 的单元测试 URL

问题描述

下面的方法检查对指定 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,但它依赖于互联网连接。测试此方法的更好方法是什么?

标签: javaunit-testingmockito

解决方案


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

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

推荐阅读