Spring Boot How to init a Bean for testing?
By:Roy.LiuLast updated:2019-08-11
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() { //...
From:一号门
Previous:Java – Convert Integer to String
COMMENTS