今天在配置JUint做Service层测试,发现Bean一直无法注入,刷了很多的博客,一直没有成功。
先附上最后成功的代码
/**
* @author Jame
* @date 2018/07/24 16:47
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = BackendApplication.class)
@ContextConfiguration(locations = { "classpath*:*-config.xml"})
public class MessageNoticeServiceImplTest {
@Resource
private MessageNoticeService messageNoticeService;
@Test
public void sendMessage() {
Assert.assertNull(messageNoticeService.sendMessage("标题","内容",10001,null));
}
}
关键点在于:
1、@SpringBootTest(classes = BackendApplication.class)
作为SpringBoot测试项目启动,标注启动的Application。亲测缺失注解和不指定Application都无法注入成功。
2、@ContextConfiguration(locations = { "classpath*:*-config.xml"})
或者是 @ContextConfiguration(locations = { "classpath:mapper-config.xml"})
引入启动需要的配置文件,这个也是我今天一直出错的源头。
项目整合了mybaits,所以Bean的注入核心配置文件其实只是mapper-config.xml
最开始用@WebAppConfiguration,失败无法注入。
然后看了一篇博客,用@TestPropertySource,失败。
继续寻找,发现@ContextConfiguration,一开始,用@ContextConfiguration(locations = { "classpath:*-config.xml"}),失败,但是看到了希望,因为报的是Invalid source 'classpath:*-config.xml'。无效的源文件,那应该就是路径问题,或者文件名问题嘛。考虑可能不允许通配符,于是改成了@ContextConfiguration(locations = { "classpath:mapper-config.xml"}),成功。但是真的不允许用通配符吗?我又去找了一下,发现原来只是通配符的匹配规则问题。在@ContextConfiguration(locations = { "classpath:*-config.xml"})的classpath后面加上一个通配符,再测试一遍,成功。
终于可以愉快的开始Service层的测试了。