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:
  1. How do I put in the username and password
  1. 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:
        1. Create a folder called config within the test folder
        1. Create the TestConfig class in the config folder
          1. Folder Structure
            Folder Structure
        1. Include in the TestConfig class an @Bean for PasswordEncoder
          1. Include the Class-level annotation below in the unit test:

            References


            © Foy Wan 2022 - 2025