Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

How to test a Spring Boot application in Java? @SpringBootTest Example

Hello guys, if you are wondering how to test your Java + Spring Boot application then you are at the right place. Earlier, I have shared best Spring Boot Courses and Spring Boot + Microservice example and in this article, I will talk about how to test your Spring boot application, mainly about writing unit test and integration test for Java and Spring boot application. Unit testing and Integration testing are two skills which separates a normal developer from a professional Java developer and when it comes to testing Spring applications many Java developer doesn't really know how to do that. If you are new to Java and Spring development but keen to learn Unit testing both Java and Spring Boot application then you have come to the right place.

Earlier, I have shared 20 Spring Boot testing questions and in this article, I will teach you how to test your Spring Boot application using both unit testing and integration testing.  With the @SpringBootTest annotation, Spring Boot gives a helpful method for firing up an application setting to be utilized in a test. 

In this step by step tutorial, we'll talk about when to utilize @SpringBootTest and when to more readily involve different devices for testing. We'll likewise investigate various ways of redoing the application setting and how to diminish test runtime.


Difference between Integration Tests vs. Unit Tests in Java

Before we begin integration tests with Spring Boot, we should characterize what separates an integration test from a unit test. While a unit test covers a solitary "unit", where a unit ordinarily is a solitary class, yet can likewise be a bunch of strong classes that is tried in blend.

An integration test can be any of the accompanying:
  • a test that covers numerous "units". It tests the connection between at least two bunches of strong classes.
  • a test that covers numerous layers. This is really a specialization of the principal case and could cover the cooperation between a business service and the determination layer, for example.
  • a test that covers the entire way through the application. In these tests, we send a solicitation to the application and make sure that it answers accurately and has changed the database state as per our assumptions.
Spring Boot gives the @SpringBootTest annotation which we can use to create an application setting containing every one of the articles we want for all of the above test types. Note, in any case, that abusing @SpringBootTest could prompt extremely lengthy running test suites.

In this way, for straightforward tests that cover numerous units we ought to rather create plain tests, basically the same as unit tests, in which we physically create the item diagram required for the test and fake away the rest. Along these lines, Spring doesn't start up an entire application setting each time the test is begun.




1. Test Slices

We can test our Spring Boot application all in all, unit by unit, and furthermore layer by layer. Utilizing Spring Boot's test cut comments we can test each layer independently.

Before we investigate the @SpringBootTest annotation exhaustively, we should investigate the test cut explanation to check assuming that @SpringBootTest is truly what you need.

The @SpringBootTest annotation stacks the total Spring application setting. Conversely, a test cut comment just loads beans expected to test a specific layer. What's more, along these lines, we can keep away from superfluous taunting and secondary effects.

How to test a Spring Boot application in Java? @SpringBootTest Annotation Example


 


2. @WebMvcTest Annotation

Our web regulators bear numerous obligations, for example, standing by listening to the HTTP demand, approving the information, calling the business rationale, serializing the result, and making an interpretation of the Exceptions to a legitimate reaction. We ought to compose tests to confirm this large number of functionalities.

The @WebMvcTest annotation test cut explanation will set up our application setting with barely an adequate number of parts and designs expected to test our web regulator layer. For example, it will set up our @controller's, @controlleradvice's, a MockMvc bean, and some other auto design.


Dependencies
The code models in this article just need the conditions to Spring Boot's test starter and to JUnit Jupiter:

dependencies { 
    testCompile('org.springframework.boot:spring-boot-starter-test') 
    testCompile('org.junit.jupiter:junit-jupiter:5.4.0') 
}


How to test a Spring Boot application? @SpringBootTest Annotation Example




3. Creating an ApplicationContext with @SpringBootTest

@SpringBootTest naturally begins looking through in the momentum bundle of the test class and afterward look through upwards through the bundle structure, searching for a class clarified with @SpringBootConfiguration from which it then peruses the setup to create an application setting. 

This class is normally our principal application class since the @SpringBootApplication comment incorporates the @SpringBootConfiguration explanation. It then, at that point, creates an application setting basically the same as the one that would be begun in a creation climate.

We can alter this application setting in various ways, as depicted in the following segment.

Since we have a full application setting, including web regulators, Spring Data stores, and data sources, @SpringBootTest is exceptionally helpful for integration tests that go through all layers of the application:


@ExtendWith(SpringExtension.class) 
@SpringBootTest 
@AutoConfigureMockMvc 
class RegisterUseCaseIntegrationTest { 
    
    @Autowired 
    private MockMvc mockMvc; 
    @Autowired 
    private ObjectMapper objectMapper; 
    @Autowired 
    private UserRepository userRepository; 
    @Test 
    void registrationWorksThroughAllLayers() throws Exception { 
        UserResource user = new UserResource("xyz", "xyz@gmail.com"); 
        mockMvc.perform(post("/forums/{forumId}/register", 42L)
                .contentType("application/json") 
                .param("sendWelcomeMail", "true") 
                .content(objectMapper.writeValueAsString(user))) 
                .andExpect(status().isOk()); 
        UserEntity userEntity = userRepository.findByName("xyz"); 
        assertThat(userEntity.getEmail()).isEqualTo("xyz@gmail.com"); 
    } 
}


Here, we moreover use @AutoConfigureMockMvc to add a MockMvc occasion to the application setting. We utilize this MockMvc object to play out a POST solicitation to our application and to check that it answers true to form.


We then, at that point, utilize the UserRepository from the application setting to confirm that the solicitation has lead to a normal change in the condition of the database.




4. Adding Auto-Configurations

Above, we've previously seen an auto-design in action:


@SpringBootTest 
@AutoConfigureMockMvc 
class RegisterUseCaseIntegrationTest { 
    ... 
}


There are part of other auto-setups accessible that each add different beans to the application setting. Here are a few other valuable ones from the documentation:

  • @AutoConfigureWebTestClient: Adds WebTestClient to the test application setting. It permits us to test server endpoints.

  • @AutoConfigureTestDatabase: This permits us to run the test against a genuine database rather than the implanted one.

  • @RestClientTest: It proves to be useful when we need to test our RestTemplates. It autoconfigures the necessary parts in addition to a MockRestServiceServer object which assists us with deriding reactions for the solicitations coming from the RestTemplate calls.

  • @JsonTest: Autoconfigures JSON mappers and classes like JacksonTester or GsonTester. Utilizing these we can check whether our JSON serialization/deserialization is working appropriately or not.




5. Why are my Integration Tests so slow?

A code base with a great deal of @SpringBootTest annotations on tests might get some margin to run. The Spring test support is sufficiently shrewd to just create an application setting once and once again use it in following tests, yet in the event that various tests need different application settings, it will in any case create a different setting for each test, which gets some margin for each test.

All of the redoing choices portrayed above will make Spring create another application setting. Thus, we should create one single arrangement and use it for all tests with the goal that the application setting can be re-utilized.

In the event that you're keen on the time your tests spend for arrangement and Spring application settings, you might need to examine JUnit Insights, which can be remembered for a Gradle or Maven work to deliver a decent report about how your JUnit 5 tests invest their energy.



That's all about how to test a Spring Boot application in Java. The @SpringBootTest is an extremely helpful strategy to set up an application setting for tests that is exceptionally close the one we'll have underway. 

There are a great deal of choices to redo this application setting, however they ought to be utilized with care since we maintain that our tests should run as near creation as could really be expected.  @SpringBootTest brings the most worth to test the entire way through the application. For testing just specific cuts or layers of the application, we have different choices accessible.

Other Java and Spring Tutorial you may like
  • How Spring MVC works internally? (answer)
  • How to upload a file in the Spring MVC application? (example)
  • Top 5 Spring Boot Annotations Java Developers should know (read)
  • Spring Data JPA Repository (JpaReposistory example)
  • 5 Courses to learn Spring Cloud for Microservices (courses)
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • Difference between @RequestParam and @PathVariable in Spring (answer)
  • How to use PropertySource in Spring Framework (Example)
  • @SpringBootApplication vs @EnableAutoConfiguration? (answer)
  • 10 Spring MVC annotations Java developer should learn (annotations)
  • Top 7  Courses to learn Microservices in Java (courses)
  • 5 Courses to Learn Spring Security for Java programmers (courses)
  • Top 5 Frameworks Java Developer Should Know (frameworks)
  • Difference between @Component@Service, and @Controller in Spring (answer)
  • 20+ Spring MVC Interview Questions for Programmers (answer)
  • Spring Data JPA @Query Example (query example)
  • Top 5 Courses to Learn and Master Spring Cloud (courses)
  • Difference between @Autowired and @Inject in Spring? (answer)
  • Top 5 Spring Cloud annotations Java programmer should learn (cloud)

Thanks for reading this article so far. If you find this Spring Boot Testing tutorial useful then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are keen to learn about Microservices with Spring Boot and looking for free online courses then you can also checkout this list of 5 best Microservice courses for beginners, where you will find free Microservice courses from Udemy, Coursera, and YouTube. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.