SSM中进行Junit单元测试时无法注入service
原创
©著作权归作者所有:来自51CTO博客作者霸道流氓的原创作品,请联系作者获取转载授权,否则将追究法律责任
场景
在SSM项目中进行Junit单元测试时调用外部的service时,在使用时打断点发现为空。
代码如下:
public class AlipayTester {
private PassOrderService passOrderService;
@Autowired
public void setPassOrderService(PassOrderService passOrderService) {
this.passOrderService = passOrderService;
}
@Test
public void alipay() {
try {
PassOrder passOrder = passOrderService.getByPrimaryKey("89387");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
然后会提示passOrderService为空。
解决
添加注解:
@RunWith(SpringJUnit4ClassRunner.class)
//告诉junit spring配置文件
@ContextConfiguration("classpath:spring.xml")
添加后代码:
@RunWith(SpringJUnit4ClassRunner.class)
//告诉junit spring配置文件
@ContextConfiguration("classpath:spring.xml")
public class AlipayTester {
private PassOrderService passOrderService;
@Autowired
public void setPassOrderService(PassOrderService passOrderService) {
this.passOrderService = passOrderService;
}
@Test
public void alipay() {
try {
PassOrder passOrder = passOrderService.getByPrimaryKey("89387");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}