我试图测试我@Service
和@Repository
类在我的项目有弹簧引导启动测试和@Autowired
不工作了,我测试的类。@ComponentScan不测试工作与弹簧引导启动测试
单元测试:
@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
类)下正常工作。该服务@ComponentScan
的和@Autowire
的罚款,我在src /主/ Java方面@RestController
类,但并没有在测试中。为了使@Autowired
正常工作,我需要在我的@Configuration
课程中再次将其添加为@Bean
。该类在其他方面的范围很好,我可以在测试中引用并实例化它。问题似乎是@ComponentScan
似乎不能正确地遍历我的测试运行器类路径中的多个条目,在这种情况下是/ target/test-classes和/ target/classes。
我使用的是IDE的IntelliJ IDEA 13
UPDATE - 这里有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'看起来像什么? – geoand
你的测试用例不是一个配置,所有这些评论的东西都是不相关的。 – chrylis
查看HelloWorldRs更新后的帖子等。 –