Friday, May 19, 2023

How to test a Spring Boot Application using JUnit, Mockito, and @SpringBootTest? Example Tutorial

Hello guys, if you are wondering how to test your Spring Boot application then you are at the right place. In the past, I have shared several Spring and Spring Boot resources like best Spring boot coursesbest Spring Boot booksSpring Boot Interview questions and even Spring Boot projects and in this article, I am going to share how to test your Spring Boot application using @SpringBoot annotation. This article will teach you essential concept for testing Spring Boot applications. It's expected that you are know about essentially the fundamentals of Java, Maven and Spring Boot (Controllers, Dependencies, Database Repository, and so on).
There is a general absence of testing in many associations. Perhaps your group is one of those groups that mean well on testing, yet it generally gets put off or forgotten as the projects get going.

Why is trying so difficult to reliably do? Testing benefits are notable, but then, for what reason is it so frequently ignored?

l think there are two or three reasons testing has a lower significance in many groups. In the first place, making, coordinating and keeping up with tests can frequently be troublesome. What's more, second, except if you're an engineer that has done a ton of testing, and seen its significance and worth, you most likely won't put it high on your need rundown to learn and make a piece of your improvement cycle.

Luckily, Spring Boot is making coordinating and working with tests simpler than any time in recent memory.




1. Getting started with Spring Boot Testing 

With regards to testing there are a few unique sorts of tests that you can write to help test and robotize the wellbeing of your application. Nonetheless, before we can begin doing any testing we want to incorporate the testing structures.

With Spring Boot, that implies we really want to add a starter to our project conditions, for testing we just have to add the spring-boot-starter-test reliance:


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





2. JUnit and Hamcrest 

The principal structure that test starter will incorporate is JUnitJUnit has been around for quite a while, and in the event that you've ever unit tried in Java, you've doubtlessly utilized this structure previously. While doing fundamental unit testing, JUnit and Spring complete one another well, as you'll find in a few forthcoming demos. 

Despite the fact that JUnit gives some declaration backing to assist with dissecting test results, Spring Boot additionally consolidates Hamcrest. This structure gives further developed test results coordinating and declarations, that when joined with JUnit permit you to computerize your testing beginning to end.


2. 1 Mockito

The following system that test starter incorporates is Mockito. At times, while testing, the code you're attempting to test is a reliance for another item. Here and there, it's basically a piece of code that is difficult to set up for a unit test. 

In such cases, utilizing a structure like Mockito to deride and nail those items is the solution. Along these lines, you can continue with your tests and afterward check what was called and utilized on that article after your test is run.


2.2 Spring Tools

Last, the test starter reliance pulls in the Spring test devices.

These incorporate explanations, test utilities, and other testing combination support that permit working with JUnit, Hamcrest, and Mockito inside the Spring climate.




3. Starting Spring Boot Project

Until the end of this article, we'll set up and working with various test perspectives in our Spring Boot application. In this segment, we will get our application and climate set-ready for testing. The main thing that requirements to happen is we really want to add the spring-boot-starter-test to our project's conditions. 

Solely after adding it, we can develop a straightforward unit test to perceive how the rudiments work. A short time later, we'll need to cover several unique ways that you can run tests inside Spring Boot. You can either create the Spring Boot project through your IDE or produce it utilizing Spring Initializr. 

In the two cases, add the web reliance, which remembers a test-starter reliance for your project if not, you'll need to physically add it:


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



While adding it physically, adding it to the lower part of the pom.xml document will make Maven pull all your test asset conditions.


One thing to note on this reliance is that it incorporates the extent of test <scope>test</scope>. That implies that when the application is packaged and bundled for organization, any conditions that are announced with the test extension are overlooked. The test scope conditions are just accessible while running being developed and Maven test modes.


Since we have our testing libraries set up, we can feel free to create a test.


4. JUnit Testing

It's the most considered normal practice for all testing related code to go in the src/test/java organizer. The Maven prime example that created the project at first incorporated a test class called for example DemoApplicationTests - in light of the name of your fundamental class, in that very bundle.

Presently we simply need something to test.

We should characterize a basic regulator in our src/fundamental/java organizer:


HomeController:

@RestController
public class HomeController {


@RequestMapping("/")
public String home() {
return "Hi World!";
}
}


This regulator has a solitary technique, returning a string, which is run when we access the base of our application. That sort of conduct is normal from this regulator, however we should test it and check whether it acts accurately:


JUnitControllerTest:

public class JUnitControllerTest {

@Test
public void testHomeController() {
    homeController = new HomeController();
    String result = homeController.home();
    assertEquals(result, "Hi World!");
    }
}

assertEquals is static technique which from the org.junit.Assert bundle, and only one of the statement strategies utilized in JUnit:
  • assertEquals :  Checks if two primitive types or objects are equal.
  • assertTrue : Checks if input condition is true.
  • assertFalse : Checks if input condition is false.
  • assertNotNull : Checks if an object isn't null.
  • assertNull : Checks if an object is null.
  • assertSame : Checks if two object references point to the same object in memory.
  • assertNotSame : Checks if two object references do not point to the same object in memory.
  • assertArrayEquals : Checks whether two arrays are equal to each other.

We get going our test by starting up our HomeController. There's compelling reason need to depend on reliance infusion for this. We're utilizing the assertEquals strategy to check whether the returned esteem from our technique matches another string.

This is a straightforward, yet useful and finished unit test. We've coordinated the testing systems, created a JUnit test by hailing the technique with a @Test comment after which we played out a test declaration.

Presently, we should run the test and notice the outcome - and there are various ways of running tests:

The primary way is to just right-tap overall test, or the test name on the off chance that you wish to run a solitary test. Thereafter, select "Run as JUnit". This initiates the test on your IDE.

How to test a Spring Boot Application using JUnit, Mockito, and @SpringBootTest? Example Tutorial


5. Spring Boot Starter Test Example

Step 1: Open Spring Initializr https://start.spring.io/.

Step 2: Provide the Group name and Artifact Id. We have given Group name com.example and Artifact spring-boot-test-model.

Step 3: Add the Spring Web dependency.

Step 4: Click on the Generate button. At the point when we click on the Generate button, it wraps every one of the details connected with the project and downloads a Jar document to our neighborhood framework.

Step 5: Extract the downloaded Jar record.

Step 6: Import the folder to STS. It requires an time to import.

File - > Import - > Existing Maven Projects - > Browse - > Select the folder spring-boot-test-example
- > Finish

In the wake of importing the project, we can see the accompanying project catalog in the Package Explorer segment of the STS. We can find in the above catalog that it contains a test record named SpringBootTestExampleApplicationTest.java in the organizer src/test/java.


SpringBootTestExampleApplicationTest.java

package com.javatpoint.springboottestexample; 
import org.junit.jupiter.api.Test; 
import org.springframework.boot.test.context.SpringBootTest; 

@SpringBootTest 
class SpringBootTestExampleApplicationTests { 

    @Test 
    void contextLoads() { 
    } 
}


The above code carries out two comment naturally: @SpringBootTest, and @Test.
  • @SpringBootTest: It applies on a Test Class that runs Spring Boot based tests. It gives the accompanying elements far beyond the normal Spring TestContext Framework:
  • It involves SpringBootContextLoader as the default ContextLoader if no particular @ContextConfiguration(loader=...) is characterized.
  • It naturally looks for a @SpringBootConfiguration when settled @Configuartion isn't utilized, and no explicit classes are determined.
  • It offers help for various WebEnvironment modes.
  • It enlists a TestRestTemplate or WebTestClient bean for use in web tests that are utilizing the webserver.
  • It permits application contentions to be characterized utilizing the args property.

Step 7: Open the SpringBootTestExampleApplicationTest.java file and run it as Junit Test.


That's all about how to test your SpringBoot application using JUnit, SpringBootTest, and @Test annotation. In this article, You have developed a Spring application and tried it with JUnit. Testing is an important skill and learning how to test your spring boot application can really enhance your profile and make you a better developer.

Other Spring Framework articles you may like to explore 

    Thanks for reading this article so far. If you find this Spring Boot +  JUnit + Hamcrest + Mockito example useful, please share them with your friends and colleagues. If you have any questions or feedback, then please drop a note.   

    P. S. - If you want to learn Spring Boot in depth then you can also checkout these 10 advanced Spring framework courses where I have shared a couple of advanced Spring Boot testing courses as well. You can join them to master unit and integration testing in Spring Boot and Java. 

    No comments :

    Post a Comment