我正在尝试使用 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 方法的类)可以正常工作。在我的 src/main/java 端的类中,服务@ComponentScan
和@Autowire
's 很好@RestController
,但在测试中没有。我需要@Bean
在我的@Configuration
课堂上再次添加它@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();
}
}