Java对WebService实现类的方法做单元测试

来源:互联网 发布:无root一键免流软件 编辑:程序博客网 时间:2024/05/01 03:53

作者:Java兔

学会了使用Junit4对webService接口做单元测试后,这次在service实现类中写了个方法,不是接口,写好方法后想写个单元测试测试一下,却忽然不知道该如何测试起来。由于这是个独立的方法,不是个接口,以为只要new一个实现类调用下这个方法即可,却发现方法中涉及到的mapper对象均为null,即注入失败,不知该如何是好来。后发现,不需要new这个实现类,而是要注入这个实现类,就能成功进行单元测试了。工作中只做过注入接口,现在才发现实现类也是可以注入的,真是惭愧。由此,联想到既然实现类也能注入使用,那我们写接口的好处是啥呢?心中答案有很多,但总觉得没有抓住这个问题的核心,便上网百度了一下,寻寻觅觅算是找到了自认为满意的答案:多态,虽然现在公司的接口99%都只对应一种实现吧,意义似乎不是很大哎,懒得去纠结了=。=下面是这次单元测试的示例:

待测试的方法

@Autowiredprivate DeptMapper deptMapper;/** * 获取咨询电话 * @param deptCode 部门编码 * @return 咨询电话 */public String getPhoneNumber(String deptCode) {    DeptEntity deptEntity = null;    if (deptCode == null || deptCode.equals("")) {        log.error("部门编码为空,获取咨询电话失败,默认返回空字符串");        return "";    }    int length = deptCode.length();    //如果是总公司,则直接获取总公司的咨询电话    if (length == 4) {        deptEntity = deptMapper.getDeptInfo(deptCode);    //如果是分公司及以下,则优先选择分公司的咨询电话    } else {        DeptEntity deptEntity1 = deptMapper.getDeptInfo(deptCode.substring(0,4));        DeptEntity deptEntity2 = deptMapper.getDeptInfo(deptCode.substring(0,6));        if (deptEntity2 == null || StringUtils.isEmpty(deptEntity2.getDeptTelephone())) {            deptEntity = deptEntity1;        } else {            deptEntity = deptEntity2;        }    }    if (deptEntity == null) {        log.warn("该部门的咨询电话为空:{},默认返回空字符串", deptCode);        return "";    } else {        String phoneNumber = deptEntity.getDeptTelephone();        log.info("部门:{}的咨询电话为:{}",deptCode,phoneNumber);        return phoneNumber;    }}

测试方法

/** * @Author huangjp * @create in 2017-8-15 17:01 * @Description : 获取咨询电话接口测试类 **/@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"classpath:spring-core.xml","classpath:spring-mybatis.xml",        "classpath:spring-ht.xml","classpath:spring-task.xml"})public class BillingDispatchServiceImplTest {    @Autowired    private BillingDispatchServiceImpl billingDispatchServiceImpl;    @Test    public void testGetPhoneNumber() throws Exception {        String deptCode = "000101";        String phoneNumber = billingDispatchServiceImpl.getPhoneNumber(deptCode);        Assert.assertNotNull("获取咨询电话接口返回null,测试失败",phoneNumber);    }}

参考资料:
Java 接口(interface)的用途和好处;