Java 为什么@Configuration类没有在Spring引导测试中运行?
我有一个位于Java 为什么@Configuration类没有在Spring引导测试中运行?,java,spring,spring-mvc,spring-boot,Java,Spring,Spring Mvc,Spring Boot,我有一个位于com.app.config的Spring Boot@Configuration类和一个位于com.app.controller的控制器,我的测试(在测试目录中)位于com.app.controller。当我运行它时,从未使用过配置类 package com.app.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Com
com.app.config
的Spring Boot@Configuration
类和一个位于com.app.controller
的控制器,我的测试(在测试目录中)位于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...
}
}
@组件扫描
用于@配置
类。尝试用@springbootest
替换测试类中的内容,加载和配置应用程序上下文您可以进行以下更改
在配置文件中,添加@ComponentScan(“您的包路径”)
在测试文件中,添加@ContextConfiguration(classes=ConfigurationClass.class)
有关更多信息,请参阅此
import org.springframework.context.annotation.ComponentScan;
@Configuration
@EnableWebMvc
@ComponentScan("com.app")
public class ValidationConfig {
import org.springframework.test.context.ContextConfiguration;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ValidationConfig.class)
public class TestAumController {