java - 带有 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,但它依赖于互联网连接。测试此方法的更好方法是什么?
解决方案
您可以验证您的模拟实体是否具有预期状态或执行某些行为。
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());
推荐阅读
- excel - 分别对多个 Excel 列进行数字排序
- selenium - 使用 WebDriver 在移动设备上进行 Galen 测试
- opencv - dnn 模块中使用哪个 caffe 版本的 opencv?
- ios - 如何以编程方式在 TableView 上添加 WKWebView
- javascript - Google Apps 脚本 – 从文件夹 ID 获取文件夹名称?
- twitter-bootstrap - 如何使引导事件在 vue 中工作
- java - Java - Hibernate:基于另一个字段生成序列列
- javascript - Angular 6 - 通过 API 使用用户位置(OpenLayers)
- scala - 斯卡拉/火花集合
- python - 在python mysql中将图像插入数据库