Spring Boot – How to init a Bean for testing?

In Spring Boot, we can create a @TestConfiguration class to initialize some beans for testing class only.

P.S Tested with Spring Boot 2

1. @TestConfiguration + @Import

This @TestConfiguration class will not pick up by the component scanning, we need to import it manually.

TestConfig.java

package com.mkyong;

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;

import java.time.Duration;

@TestConfiguration
public class TestConfig {

    @Bean
    public RestTemplateBuilder restTemplateBuilder() {

        return new RestTemplateBuilder()
                .basicAuthentication("mkyong", "password")
                .setConnectTimeout(Duration.ofSeconds(5));
    }
}
RestTemplateTest.java

package com.mkyong;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@Import(TestConfig.class)
public class RestTemplateTest {
    
    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void post_user_ok() {
        //...
    }

}

2. @TestConfiguration + Inner Static Class

Alternatively, create a inner class like this :

RestTemplateTest.java

package com.mkyong;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.Duration;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RestTemplateTest {

    @TestConfiguration
    static class TestConfig {

        @Bean
        public RestTemplateBuilder restTemplateBuilder() {

            return new RestTemplateBuilder()
                    .basicAuthentication("mkyong", "password")
                    .setConnectTimeout(Duration.ofSeconds(5));
        }
        
    }

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void post_user_ok() {
        //...
    }

}

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar