Write RestController tests quickly with Spring Boot + Spock

Test content

Validate the JSON-formatted response body returned by RestController.

environment

Spring Boot:2.1.1 Spock:1.2 Groovy:2.5 OS:Windows10

Preparation

Add the required libraries for Spring Boot + Spock testing. By writing the dependency on spock-core, the libraries around Groovy will also drop. Also, if you don't have spock-spring, you can't use @Autowired etc. in Spock (Groovy), so add this if necessary.

pom.xml


<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>org.spockframework</groupId>
	<artifactId>spock-core</artifactId>
	<version>1.2-groovy-2.5</version>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>org.spockframework</groupId>
	<artifactId>spock-spring</artifactId>
	<version>1.2-groovy-2.5</version>
	<scope>test</scope>
</dependency>

The URL and response body of the RestController you want to test

The URL and response body of the RestController you want to test are as follows.

URL:
  http://localhost:8080/employees

Response:
  Status Code 200 OK
  [
    {
      "id": "00000001",
      "name": "Employee A",
      "department": {
        "id": "001",
        "name": "Department A"
      }
    },
    {
      "id": "00000002",
      "name": "Employee B",
      "department": {
        "id": "001",
        "name": "Department A"
      }
    }
  ]

Controller class you want to test

I will omit the steps from EmployeeService # getEmployees, but the Controller you want to test is as follows.

EmployeeController.java


@RestController
public class EmployeeController {

	@Autowired
	private EmployeeService employeeService;

	@GetMapping(value = "/employees")
	public ResponseEntity<List<Employee>> getEmployees() {
		List<Employee> employeeList = employeeService.getEmployees();
		if (CollectionUtils.isEmpty(employeeList)) {
			return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);	
		}
		return new ResponseEntity<List<Employee>>(employeeList, HttpStatus.OK);
	}
}

Test class

Verify using Groovy's Json Slurper and Json Builder.

//ApplicationContext is loaded, but Web environment etc. is not provided
@SpringBootTest(webEnvironment = WebEnvironment.NONE)

//Start the server on a random port
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)


//The default is this, you don't have to write it. A simulated web environment is provided without starting the server
// @AutoConfigureMockMvc or@Can be used in combination with AutoConfigureWebTestClient
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)


//The actual web environment is provided. The embedded server starts and the configured port (application).Listen on properties) or on the default port 8080
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)

EmployeeControllerTest.groovy


@SpringBootTest
@AutoConfigureMockMvc
class EmployeeControllerTest extends Specification {

	@SpyBean
	private EmployeeService employeeService

	@Autowired
	MockMvc mockMvc

	@Unroll
	def "EmployeeController -Normal system-2 employees return"() {

		given:
		def department = new Department("001", "Department A");
		def employeeList = new ArrayList<Employee>() { {
						this.add(new Employee("00000001", "Employee A", department));
						this.add(new Employee("00000002", "Employee B", department));
					}
				}
		def jsonBuilder = new JsonBuilder(employeeList)
		def jsonSlurper = new JsonSlurper()

		when:
		def actual = mockMvc.perform(MockMvcRequestBuilders.get("/employees")).andReturn().getResponse()

		then:
		actual.getStatus() == HttpStatus.OK.value
		jsonSlurper.parseText(actual.getContentAsString()) == jsonSlurper.parseText(jsonBuilder.toPrettyString())
	}

	@Unroll
	def "EmployeeController -Normal system-Nothing returns"() {

		given:
		when(employeeService.getEmployees()).thenReturn(null)

		when:
		def actual = mockMvc.perform(MockMvcRequestBuilders.get("/employees")).andReturn().getResponse()

		then:
		actual.getStatus() == HttpStatus.NO_CONTENT.value
		actual.getContentAsString() == ""
	}
}

In this article, I used Groovy's Json Slurper and Json Builder to verify JSON. Alternatively, [Spring Boot @JsonTest](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring You can also verify JSON by using -boot-applications-testing-autoconfigured-json-tests) etc.

Source used in this article: https://github.com/kenichi-nagaoka/spock-sample/tree/feature/1

that's all.

reference

Recommended Posts

Write RestController tests quickly with Spring Boot + Spock
Write tests with Minitest
Download with Spring Boot
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
Generate barcode with Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Get started with Spring boot
Run LIFF with Spring Boot
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
Create microservices with Spring Boot
Send email with spring boot
Create an app with Spring Boot 2
Database linkage with doma2 (Spring boot)
Write test code in Spring Boot
Spring Boot programming with VS Code
Until "Hello World" with Spring Boot
Get validation results with Spring Boot
Frequent annotations for Spring Boot tests
(Intellij) Hello World with Spring Boot
Create an app with Spring Boot
Google Cloud Platform with Spring Boot 2.0.0
Check date correlation with Spring Boot
I tried GraphQL with Spring Boot
[Java] LINE integration with Spring Boot
Beginning with Spring Boot 0. Use Spring CLI
I tried Flyway with Spring Boot
Message cooperation started with Spring Boot
Spring Boot gradle build with Docker
[Beginner] Let's write REST API of Todo application with Spring Boot
Processing at application startup with Spring Boot
Spring with Kotorin --2 RestController and Data Class
Hello World with Eclipse + Spring Boot + Maven
Send regular notifications with LineNotify + Spring Boot
Perform transaction confirmation test with Spring Boot
Try using Spring Boot with VS Code
Start web application development with Spring Boot
Launch Nginx + Spring Boot application with docker-compose
I tried Lazy Initialization with Spring Boot 2.2.0
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Asynchronous processing with Spring Boot using @Async
Implement paging function with Spring Boot + Thymeleaf
Write tests for JavaFX applications with TestFX
(IntelliJ + gradle) Hello World with Spring Boot
Use cache with EhCashe 2.x with Spring Boot
Form class validation test with Spring Boot
Run WEB application with Spring Boot + Thymeleaf
Achieve BASIC authentication with Spring Boot + Spring Security
Spring Boot environment construction with Docker (January 2021 version)
Create a website with Spring Boot + Gradle (jdk1.8.x)
Configure Spring Boot application with maven multi module
Test controller with Mock MVC in Spring Boot
Asynchronous processing with regular execution in Spring Boot