简体   繁体   中英

Need to Start Tomcat server for test Junit test case

Hello I have write a juint test case for rest api using HttpUriRequest. The Test case gives the proper result but the issue is that i need to run the tomcat server to test the junit test case. why??

Here is my Code:

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

This test case is working fine but when i stop the server the test case is not executed. Is there is any way to test this case without run the server?? Thanks

I think you misunderstood the meaning of "unit tests". If you are doing an http request to a running server, you are testing the whole server, and not just some separate unit.

If you want to test the logic inside your controller, just create the controller object manually and call the corresponding method.

If you want to test you api endpoints, spring provides various annotation and different ways in which you could test your appplication. Like:

  1. You could start up the server during test case, initialize the spring application context and then test the api by hitting it to assert the result.
  2. You could just use the spring annotation @SpringBootTest along with @AutoConfigureMockMvc to setup the application context without starting the server to test your application end to end.
  3. Yet another approach when you do not want to test the entire application but just need to test the web layer is to use the annotation @WebMvcTest . In this case you need to mock the service layer and any other beans that might be needed to get the desired result.

You can use the annotation @SpringBootTest to tell spring that it should start up the server and have the application context configured to run your test.

The @SpringBootTest annotation tells Spring Boot to look for a main configuration class (one with @SpringBootApplication , for instance) and use that to start a Spring application context.

In that case, you won't have to start your server manually spring will take care of everything and once the tests are done it will stop the server as well.I haven't tried compiling or running the code but use like:

 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
 public class HttpRequestTest {

    @LocalServerPort
    private int port;

    final String versionNumber = "v1";

    final String pathUrl = "/dgcontroller/services/restAPIs/";

    final String sessionId = "2";

    @Test
    public void idpsTest() throws ClientProtocolException, IOException {
        String baseUrl = "http://localhost:"+port+pathUrl;
        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);
    }

}

This should work as long as you have the following dependency in your pom.xml :

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

The server is needed because you are making tests against the URLs.

The only way you can do this is to mock the server. There are many different mocking libraries out there for Java, like Mockito or EasyMock, but they all allow you to provide fake responses from the server.

From the test case you pasted, it does not make sense to perform such tests, since you seem to be checking that the actual server replies and do nothing with the response. Mocking the server is very useful to test API clients, but you don't seem to be testing that.

You have two options here:

  • Test the functionality inside the endpoint with an unit test without involving the server at all
  • Create some pre-integration and post-integration hooks that starts and stops the server for you while testing. You can easily do this with Maven or Gradle (check Starting of the Apache tomcat server before integration test )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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