Category: TDD (Test Driven Development)

Spring Boot Test and Spring Security: Perform Http Basic Authentication with TestRestTemplate

 

What is HTTP Basic Authentication?

If you want to refresh your knowledge on HTTP Basic Authentication, please click here to refer my article on that.

Here i am going to show you how to execute spring test cases on REST endpoints that are secured with Spring Security and required HTTP Basic Authentication.  Here we are going to use the TestRestTemplate as the REST client for invoking REST endpoints.

 

TestRestTemplate

TestRestTemplate is a convenience alternative to Spring’s RestTemplate that is useful in integration tests. If you use the @SpringBoootTest annotation , with one of the following webEnviroment attribute, you can use fully configured TestRestTemplate in your Test class.

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
                        OR
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)

 

There are different ways that can be used to perform Basic Authentication with TestRestTemplate.

  1.  Authentication headers
  2.  ‘withBasicAuth’ method
  3.  With Authenticated TestRestTemplate object.

Lets look at each of those approaches in detailed as follows.

Continue reading “Spring Boot Test and Spring Security: Perform Http Basic Authentication with TestRestTemplate”

Spring Boot Test: Writing Unit Tests for the Controller Layers with @WebMvcTest

 

Unit Tests and Integration Tests

@SpringBootTest annotation will load the fully ApplicationContext. Therefore it is highly used for writing the integration testing in web server environment. This will not use slicing and scan for all the stereotype annotations (@Component@Service, @Respository and @Controller / @RestController) and loads the full application context. Therefore this is more good at in the context of writing integration testing for the application.

@WebMvcTest annotation will load only the controller layer of the application. This will scan only the @Controller/ @RestController annotation and will not load the fully ApplicationContext. If there is any dependency in the controller layer (has some dependency to other beans from your service layer), you need to provide them manually by mocking those objects.

Therefore @SpringBootTest is widely used for Integration Testing purpose and @WebMvcTest is used for controller layer Unit testing.

Continue reading “Spring Boot Test: Writing Unit Tests for the Controller Layers with @WebMvcTest”