Unit Test and Integration Test for secured REST API
date
Aug 2, 2022
slug
unit-and-integration-test-for-secured-rest-api
status
Published
tags
API
REST
Spring Boot
Spring Security
Test
summary
type
Post
Background
I’ve secured my Dog REST API using
Basic Authentication
with Spring Security
.Problem
Now I want to create a unit test and an integration test for my API, but I have two problems with them:
- How do I put in the username and password
- I got the error below when I ran the unit test:
What’s wrong
For the second problem, The error was occurring because in the unit test class I was using
@WebMvcTest
and it was only going to scan the Controller
I’ve defined and the MVC infrastructure
So other
@Bean
that were defined outside the Controller
and that were needed as is the case of the one that is present in the PasswordEncoder
have to be defined manually.Solution
How do I put in the username and password
- Unit Test
- Integration Test
Error Failed to load ApplicationContext
when running unit test
To add the
@Bean
referring to the PasswordEncoder
in the unit test, follow the steps below:- Create a folder called
config
within the test folder
- Create the
TestConfig
class in theconfig
folder

- Include in the
TestConfig
class an@Bean
forPasswordEncoder
- Include the Class-level annotation below in the unit test: