JUnit tests for the Spring Boot application

Spring Boot provides two modules for test support—sprint-boot-test and spring-boot-test-autoconfigure. spring-boot-test contains core items, and spring-boot-test-autoconfigure supports auto-configuration for tests. These modules have a number of utilities and annotations to help when testing your application. It is very simple to add these modules in the Spring Boot application by adding the spring-boot-starter-test starter dependency in your Maven file. This starter imports both Spring Boot test modules as well as JUnit, AssertJ, Hamcrest, and a number of other useful libraries. Let's see the following Maven dependency to include test support in the Spring Boot application:

<dependency> 
   <groupId>org.springframework.boot</groupId> 
   <artifactId>spring-boot-starter-test</artifactId> 
   <scope>test</scope> 
</dependency> 

The preceding Maven dependency will add the following libraries to your Spring Boot application:

  • JUnit: This is related to unit testing Java applications
  • Spring test and Spring Boot test: They add utilities and integration-test support for Spring Boot applications
  • AssertJ: It is an assertion library
  • Hamcrest: This library is related to constraints or predicates
  • Mockito: It is a Java mocking framework
  • JSONassert: This library is used to assert in JSON support
  • JsonPath: XPath for JSON

These libraries are useful for writing tests. Spring Boot provides an annotation, @SpringBootTest. This annotation can be used as an alternative to the @ContextConfiguration annotation of the Spring test module. This annotation is used to create ApplicationContext in your tests using SpringApplication. Let's see the following class:

package com.dineshonjava.accountservice; 
 
import static org.junit.Assert.assertFalse; 
import static org.junit.Assert.assertTrue; 
 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.boot.test.context.SpringBootTest; 
import org.springframework.test.context.junit4.SpringRunner; 
 
import com.dineshonjava.accountservice.service.AccountService; 
 
@RunWith(SpringRunner.class) 
@SpringBootTest 
public class AccountServiceApplicationTests { 
    
   @Autowired 
   AccountService accountService; 
    
   @Test  
   public void findAccountByAccountId() { 
   assertTrue(accountService.findAccountByAccountId(100).getBalance().intValue() == 3502); 
   } 
    
   @Test  
   public void findAllByCustomerId() { 
         assertFalse(accountService.findAllByCustomerId(1000).size() == 
3); } }

The class is annotated with the @SpringBootTest annotation, no need to add the @ContextConfiguration annotation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.180.43