首页 > 解决方案 > 需要启动 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);
    }
}

这个测试用例工作正常,但是当我停止服务器时,测试用例没有执行。有没有办法在不运行服务器的情况下测试这种情况?谢谢

标签: javamockitojunit5

解决方案


我认为您误解了“单元测试”的含义。如果您正在对正在运行的服务器发出 http 请求,那么您正在测试整个服务器,而不仅仅是某个单独的单元。

如果要测试控制器内部的逻辑,只需手动创建控制器对象并调用相应的方法即可。


推荐阅读