Load different application.yml in SpringBoot Test

前端 未结 11 1113
天涯浪人
天涯浪人 2020-11-30 22:09

I\'m using a spring boot app which runs my src/main/resources/config/application.yml.

When I run my test case by :

@RunWith(SpringJUnit4ClassRunner.c         


        
11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 23:06

    We can use @SpringBootTest annotation which loads the yml file from src\main\java\com...hence when we execute the unit test, all of the properties are already there in the config properties class.

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class AddressFieldsTest {
    
        @InjectMocks
        AddressFieldsValidator addressFieldsValidator;
    
        @Autowired
        AddressFieldsConfig addressFieldsConfig;
        ...........
    
        @Before
        public void setUp() throws Exception{
            MockitoAnnotations.initMocks(this);
            ReflectionTestUtils.setField(addressFieldsValidator,"addressFieldsConfig", addressFieldsConfig);
        }
    
    }
    

    We can use @Value annotation if you have few configs or other wise we can use a config properties class. For e.g

    @Data
    @Component
    @RefreshScope
    @ConfigurationProperties(prefix = "address.fields.regex")
    public class AddressFieldsConfig {
    
        private int firstName;
        private int lastName;
        .........
    

提交回复
热议问题