为什么@Configuration类没有在Spring Boot测试中运行?

时间:2017-09-17 20:19:28

标签: java spring spring-mvc spring-boot

我有一个Spring Boot @Configuration类,它位于com.app.config' and a controller located at com.app.controller and my test (in the tests directory) is at com.app.controller`。当我运行它时,从不使用配置类。

package com.app.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;


@Configuration
@EnableWebMvc
@ComponentScan("com.app")
public class ValidationConfig {

    @Bean
    public Validator validator() {

        //The breakpoint here is never called!
        return new LocalValidatorFactoryBean();
    }
}

测试类:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.validation.Validator;

@RunWith(SpringRunner.class)
@ComponentScan({"com.app","com.app.config"})
public class TestAumController {

    //...elided...

    @Autowired
    private Validator validator;

    @Test
    public void testController() throws Exception {
        //..edlided...
    }
}

2 个答案:

答案 0 :(得分:2)

@ComponentScan适用于@Configuration个班级。尝试用@SpringBootTest替换测试类中的那个,它会加载和配置应用程序上下文

答案 1 :(得分:0)

您可以进行以下更改。

在配置文件中,添加@ComponentScan("Your Package path")

import org.springframework.context.annotation.ComponentScan;               

@Configuration
@EnableWebMvc
@ComponentScan("com.app")
public class ValidationConfig {

在测试文件中,添加@ContextConfiguration(classes = ConfigurationClass.class)

import org.springframework.test.context.ContextConfiguration;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ValidationConfig.class)
public class TestAumController {

有关详情,请参阅此link