繁体   English   中英

使用Mockito的单元测试URL

[英]Unit Test URL with 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连接。 有什么更好的方法来测试此方法?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM