场景

在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();
}

}
}