Skip to content

Controller Testing

Somkiat Puisungnoen edited this page Dec 28, 2020 · 5 revisions

How to test REST Controller ?

Run test in command line

$mvnw clean test

1. Testing with @SpringBootTest

UserControllerSpringBootTest.java

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;

import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.*;

@SpringBootTest(webEnvironment = RANDOM_PORT)
class UserControllerSpringBootTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    void getUserById() {
        // Call API
        UserResponse response = restTemplate.getForObject("/users/1", UserResponse.class);

        // Assert
        assertEquals(1,response.getId());
        assertEquals("Demo",response.getName());
        assertEquals(40,response.getAge());
    }
}

2. Testing with @WebMvcTest

UserControllerWebMvcTest.java

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import static org.junit.jupiter.api.Assertions.*;

@WebMvcTest(UserController.class)
class UserControllerWebMvcTest {

    @Autowired
    private MockMvc mvc;

    @Test
    void getUserById() throws Exception {
        // Call API
        MvcResult mvcResult = this.mvc.perform(get("/users/1").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk()).andReturn();

        // Convert response to JSON object
        String response = mvcResult.getResponse().getContentAsString();
        ObjectMapper mapper = new ObjectMapper();
        UserResponse userResponse = mapper.readValue(response, UserResponse.class);

        // Assert
        assertEquals(1, userResponse.getId());
        assertEquals("Demo", userResponse.getName());
        assertEquals(40, userResponse.getAge());
    }
}

Working with Code coverage with Jacoco

pom.xml

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.7.5.201505241946</version>
    <configuration>
        <destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
        <dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
    </configuration>
    <executions>
        <execution>
            <id>jacoco-initialize</id>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <execution>
            <id>jacoco-site</id>
            <phase>package</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>${java.version}</source>
        <target>${java.version}</target>
    </configuration>
</plugin>

Run with command line

$mvnw clean package

Open jacoco report target/site/jacoco/index.html