java - 需要启动 Tomcat 服务器进行测试 Junit 测试用例
问题描述
您好,我已经使用 HttpUriRequest 为 rest api 编写了一个 juint 测试用例。测试用例给出了正确的结果,但问题是我需要运行 tomcat 服务器来测试 junit 测试用例。为什么??
这是我的代码:
package com.dataguise.webservices;
import static org.junit.jupiter.api.Assertions.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import com.dataguise.webservices.beans.DgException;
class RestAPIsTest {
final String versionNumber = "v1";
final String baseUrl = "http://localhost:10181/dgcontroller/services/restAPIs/";
final String sessionId = "2";
@Test
public void idpsTest() throws ClientProtocolException, IOException {
HttpUriRequest request = new HttpGet(baseUrl + versionNumber + "/idps");
request.addHeader("sessionId", sessionId);
HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
System.out.println(">>>>>>>>>>>>>>>." + httpResponse.getStatusLine().getStatusCode());
assertEquals(200, httpResponse.getStatusLine().getStatusCode());
// Getting Json From Http Response
String json = EntityUtils.toString(httpResponse.getEntity());
System.out.println(">>>>>>>>>>>>>>>." + json);
}
}
这个测试用例工作正常,但是当我停止服务器时,测试用例没有执行。有没有办法在不运行服务器的情况下测试这种情况?谢谢
解决方案
我认为您误解了“单元测试”的含义。如果您正在对正在运行的服务器发出 http 请求,那么您正在测试整个服务器,而不仅仅是某个单独的单元。
如果要测试控制器内部的逻辑,只需手动创建控制器对象并调用相应的方法即可。
推荐阅读
- javascript - Express js路由器不工作
- javafx - JavaFX学习资料的建议
- xamarin.android - Xamarin Android 应用程序中的 Autofac 错误
- laravel - 从作业中发送 Guzzle http 请求后没有响应
- reactjs - redux-persist 和 AsyncStorage 有什么区别?
- java - Java,将相同的对象映射到不同的对象
- android - 类似 Snapchat 的 Viewpager 动画
- php - Laravel 在模型中定义多个外键并出现错误
- swift - 类型开关模式
- python - 如何从包含分页的网站中提取链接?(使用硒)