【发布时间】:2014-07-05 06:44:09
【问题描述】:
我正在尝试使用 spring-boot-starter-test 在我的项目中测试我的@Service 和@Repository 类,而@Autowired 不适用于我正在测试的类。
单元测试:
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = HelloWorldConfiguration.class
//@SpringApplicationConfiguration(classes = HelloWorldRs.class)
//@ComponentScan(basePackages = {"com.me.sbworkshop", "com.me.sbworkshop.service"})
//@ConfigurationProperties("helloworld")
//@EnableAutoConfiguration
//@ActiveProfiles("test")
// THIS CLASS IS IN src/test/java/ AND BUILDS INTO target/test-classes
public class HelloWorldTest {
@Autowired
HelloWorldMessageService helloWorldMessageService;
public static final String EXPECTED = "je pense donc je suis-TESTING123";
@Test
public void testGetMessage() {
String result = helloWorldMessageService.getMessage();
Assert.assertEquals(EXPECTED, result);
}
}
服务:
@Service
@ConfigurationProperties("helloworld")
// THIS CLASS IS IN /src/main/java AND BUILDS INTO target/classes
public class HelloWorldMessageService {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message=message;
}
}
单元测试中注释的类注释代表了我为使其正常工作所做的各种事情。测试和项目包位于相同的包路径中,@ComponentScan 从我的入口点可以正常工作(@RestController 带有 main 方法的类)。服务 @ComponentScan 和 @Autowire 在我的 src/main/java 端的 @RestController 类中很好,但在测试中没有。我需要在我的@Configuration 类中再次将其添加为@Bean,以便@Autowired 工作。否则该类在范围内就好了,我可以从测试中引用和实例化它。问题似乎是 @ComponentScan 似乎没有正确遍历我的测试运行程序类路径中的多个条目,在本例中是 /target/test-classes 和 /target/classes。
我使用的 IDE 是 IntelliJ IDEA 13。
更新 - 这是 HelloWorldRs 及其配置:
@RestController
@EnableAutoConfiguration
@ComponentScan
public class HelloWorldRs {
// SPRING BOOT ENTRY POINT - main() method
public static void main(String[] args) {
SpringApplication.run(HelloWorldRs.class);
}
@Autowired
HelloWorldMessageService helloWorldMessageService;
@RequestMapping("/helloWorld")
public String helloWorld() {
return helloWorldMessageService.getMessage();
}
}
...
@Configuration
public class HelloWorldConfiguration {
@Bean
public Map<String, String> map() {
return new HashMap<>();
}
// This bean was manually added as a workaround to the @ComponentScan problem
@Bean
public HelloWorldMessageService helloWorldMessageService() {
return new HelloWorldMessageService();
}
// This bean was manually added as a workaround to the @ComponentScan problem
@Bean
public HelloWorldRs helloWorldRs() {
return new HelloWorldRs();
}
}
【问题讨论】:
-
HelloWorlsRs长什么样子? -
您的测试用例不是配置,所有那些注释的东西都与它无关。
-
查看 HelloWorldRs 等的更新帖子
-
发生了什么?你解决你的问题了吗?怎么样?
-
从
@EnableAutoConfiguration我看到你正在使用spring-boot - 这当然是一件好事。你的项目中有@SpringBootApplication吗?您可以尝试将您的测试注释为@SpringBootTest吗?
标签: java spring unit-testing spring-boot component-scan