Thursday, May 2, 2024
HomeJavaThe right way to do Integration Testing in Spring Framework? @SpringBootTest Instance...

The right way to do Integration Testing in Spring Framework? @SpringBootTest Instance Java


Howdy guys, in case you are questioning learn how to check your Spring Boot utility then you may have come to the best place. Earlier, I’ve shared in style Spring Boot Testing Interview Questions and Spring Safety Interview Questions and On this article, I’ll present you examples to check your Spring Boot utility utilizing @SpringBootTest annotation, which lets you write Integration assessments. Once I discuss spring boot integration testing, I’m speaking
about launching an utility in ApplicationContext and performing
assessments. For integration testing, Spring Framework has a particular check
module. It is known as a spring check. If we will make the most of
spring-boot, we’ll want to make use of spring-boot-starter-test, which makes use of
spring-test and different dependencies inside.

We’ll have a look at learn how to carry out integration assessments for a Spring Boot utility on this put up.

To start with, let’s perceive what integration testing is and what to check as a part of integration testing in Spring.

What to check in Integration Testing?

Right here is an instance of Integration testing setup in Spring Framework utilizing @ContextConfiguration and @SpringBootTest annotations: 

@SpringBootTest integration test Example Java

What’s @SpringBootTest annotation?

Spring-Boot
affords an @SpringBootTest annotation that extends the spring-test
part with spring-boot performance. This annotation works through the use of @SpringBootApplication to create the ApplicationContext that we make the most of in
our assessments. It launches the embedded webserver, generates an internet
setting, after which permits integration testing utilizing @Take a look at strategies.

@SpringBootTest annotation doesn’t launch a server by default. To fine-tune how your assessments run,
we’ll want so as to add the net setting property. 

There are numerous
choices:

  • Mock: (That is the default choice)Creates a mock net setting by loading an internet ApplicationContext.
  • RANDOM
    PORT
    : Gives a real net setting by loading a
    WebServerApplicationContext. The embedded server is began and listens
    on a port that’s chosen at random. For the mixing check, that is
    the one to make the most of.
  • DEFINED PORT: Gives a real net setting by loading a WebServerApplicationContext.
  • NONE: Makes use of SpringApplication to load an ApplicationContext, however doesn’t provide an internet setting.
The
@ContextConfiguration annotation was used within the Spring Take a look at Framework
to determine which spring @Configuration to load. Spring-boot, on the
different hand, doesn’t require it because it seems for the first
configuration when none is specified.

In
addition to the applying’s fundamental configuration, we might make the most of a
nested @TestConfiguration class to alter the first configuration.

Now, sufficient of the theoretical speaking. Let’s arrange our utility and carry out the identical!

3. Organising our Spring Boot Software for Testing

Let’s
create a small REST API utility and discover how integration assessments
could be written for it. We’ll develop integration assessments for the
controller and assemble a Cricketer API to generate and get Cricketer
data. We’ll use the well-known in-memory h2 DB for our assessments.

Controller: 

Right here is our Controller class which makes use of @RestController to deal with REST API requests:
@RestController
public class CricketerController {
    @Autowired
    non-public CricketerService cricketerService;

    @PostMapping("/cricketers")
    public ResponseEntity<Void> createCricketer() {
        Record<Cricketer> cricketers =  cricketerService.createCricketer();

        URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(
            "/{id}").buildAndExpand(cricketer.get(0).getId()).toUri();

        return ResponseEntity.created(location).construct();
    }

    @GetMapping("/cricketers/{cricketerId}")
    public Cricketer retrieveCricketer(@PathVariable Integer cricketerId) {
        return cricketerService.retrieveCricketer(cricketerId);

    }

}

Service:

@Element
public class CricketerService {

    @Autowired
    non-public CricketerRepository repository;


    public Record<Cricketer> createCricketer() {
        Record<Cricketer> cricketers = new ArrayList<Cricketer>();
        Record<Cricketer> savedCricketers = new ArrayList<Cricketer>();

        cricketers.add(new Cricketer("ABD", "11"));
        cricketers.add(new Cricketer("Virat King Kohli", "7"));
        cricketers.add(new Cricketer("Rohit Sharma", "10"));
        Iterable<Cricketer> itrCricketers=repository.saveAll(cricketers);
        itrCricketers.forEach(savedCricketers::add);
        return savedCricketers;
    }
    
    public Cricketer retrieveCricketer(Integer cricketerId) {
        return repository.findById(cricketerId).orElse(new Cricketer());

    }

}

Repository: 

@Repository
public interface CricketerRepository extends CrudRepository<Cricketer, Integer>{

}
How to perform integration tests with @SpringBootTest in web application in Spring

Out Take a look at Class:

Now, let’s examine how our check class seems like Spring:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CricketerControllerTests {

    @LocalServerPort
    non-public int port;

    TestRestTemplate restTemplate = new TestRestTemplate();

    HttpHeaders headers = new HttpHeaders();
    @Take a look at
    public void testCreateCricketer() throws Exception {
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> response = restTemplate.change(
        createURLWithPort("/cricketers"), HttpMethod.POST, entity, String.class);

        String precise = response.getHeaders().get(HttpHeaders.LOCATION).get(0);

        assertTrue(precise.incorporates("/cricketers"));
    } 

    @Take a look at
    public void testRetrieveCricketer() throws Exception {
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> response = restTemplate.change(
        createURLWithPort("/cricketers/1"), HttpMethod.GET, entity, String.class);

        String anticipated = "{"id":1,"identify":"ABD","description":"11"}";

        JSONAssert.assertEquals(anticipated, response.getBody(), false);
    }

    non-public String createURLWithPort(String uri) {
     return "http://localhost:" + port + uri;
    }

}

Now we have used
WebEnvironment.RANDOM PORT to spin up the applying on a random port
within the earlier code. @LocalServerPort aids in studying the present port
and setting up the URI to be accessed by the template class. As a result of
we wish ResponseEntity as a return kind, we utilized the change()
perform.

Conclusion

That is all about learn how to check Spring Boot utility and learn how to write integration check in Spring primarily based utility utilizing @SpringBootTest annotation. We
discovered learn how to assemble assessments that check a number of ranges of purposes
in a single check on this spring boot integration testing instance utilizing
Junit 5. 

They check whether or not the controller and persistence layers
talk correctly. Whereas we’re not wanted
to make the most of an actual webserver to function the applying throughout
integration testing, we might actually use Spring boot’s embedded servers.

There are a number of advantages of doing Integration testing because it not solely check your utility finish to finish but additionally provides you alternative to check a number of parts collectively. It enhances Unit testing by additionally together with Spring framework in testing and it may be merely achieved by combining JUnit with @ContextConfiguration annotation. Although it ignore Spring MVC parts which is considered one of its limitation. 

Different Java and Spring articles you might like

  • 5 Spring Boot Annotations for full-stack Java builders (tutorial)
  • 20 Spring Boot Interview Questions for Java Programmers (questions)
  • 5 programs to be taught Spring Boot and Spring Cloud ( programs)
  • 10 Spring MVC annotations Java builders ought to be taught (annotations)
  • 10 Tricks to grow to be a greater Java developer (ideas)
  • 5 Programs to be taught Spring Cloud and Microservices (programs)
  • 3 methods to alter Tomcat port in Spring Boot (tutorial)
  • 5 Spring Boot Options Each Java Developer Ought to Know (options)
  • 5 Course to Grasp Spring Boot on-line (programs)
  • 10 Programs to be taught Spring Safety with OAuth 2 (programs)
  • 10 Issues Java Developer ought to be taught (targets)
  • High 5 Programs to be taught Microservices in Java? (programs)
  • 10 Instruments Java Builders use of their day-to-day life (instruments)
  • 10 Superior Spring Boot Programs for Java Programmers (programs)
  • High 5 Books and Programs to be taught RESTful Net Service (books)
  • 3 Greatest Practices Java Programmers can be taught from Spring (finest practices)

Thanks for studying this text up to now. If you happen to discovered this Java +
Spring Boot + Integration Testing Tutorial helpful and useful then
please share them along with your colleagues and mates. When you have any
questions or suggestions then please drop a notice.          

P. S. – In case you are new to Spring Boot and need to find out about Spring Boot and on the lookout for a free Spring Boot on-line course, I additionally suggest you be part of the Introducing Spring Boot (FREE ) class by Dan Vega on Udemy. It is the most effective free programs to be taught Spring Boot for Java builders. 
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments