我試圖測試我@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更新後的帖子等。 –