Spring Boot with 3 styles of tests – Example

If you want to see how to integration test, how to test rest api with mock, and  how to just mock , this page is for you

This example is a part of  Spring Boot with all examples

Full Code with Spring Boot 1.5.9.RELEASE:

13_spring-boot-test.zip

What you need for run this:

  • Maven 3
  • Java 8

What the code will do:

  • Show how to do integration test
  • Show how to test rest api with mock
  • Show how to just moock

Explain:

This is the file structure:

This service will just return “Count  result: [number]” when you call http://localhost:8080/api/count.

CountService.count() will just count and return int.

TestRestController.showCount() will just call CountService and add “Count result:”

Assume that our target test is TestRestCountroller. In other words, we want to test logic in TestRestController.

This is pom.xml

TestRestControllerTest1 will just try to test TestRestCountroller by mocking CountService. This is the code:

The keys are:

  • Line 13: @RunWith(MockitoJUnitRunner.class) to tell that we are going to use Mockito
  • Line 16: @Mock to create a mock object to mockCountService
  • Line 19: @InjectMock to inject mockCountService to “countService” in TestRestController object (the “target” object)

The problem with this test is that you cannot prove that you correctly map “@GetMapping(“/api/count”)” in TestRestController. But we have the solution in TestRestControllerTest2

TestRestControllerTest2 will mock CountService but it simulate a call test via rest api, let see the code:

 

The keys are:

  • Line 17 @RunWith(SpringRunner.class) to tell that it will use SpringRunner to test
  • Line 18 @WebMvcTest(TestRestController.class) to tell the target controller to test , this case is TestRestController
  • Line 30 We mock the result to return 100
  • Line 33 We use “mvc” to simulate a call the “/api/count”
  • Line 34 We get the result of the call

The most important thing about this style of test is that you can mock CountService to behave as we want.

TestRestControllerTest3 will do the full integration test, nothing will be mocked.

The keys are:

  • Line 13 @RunWith(SpringRunner.class) to tell that it will use SpringRunner to test
  • Line 14 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) to tell that we will use random port wen start Spring Boot
  • Line 26-32 We use “restTemplate” to do http call and get the results

Try:

You can just run tests.

Note that TestRestControllerTest2 and 3 will start Spring Boot.