PowerMock学习之PoweMock的入门(二)

前言

在上一篇《PowerMock学习之PoweMock的入门(一)》文章中,已经简单说起一些关于powermock的用法,可是入门还未完,我还要坚持把它学习并坚持更新到博客中。html

Mock中的API

ps:仅更新此次案例中使用的api说明。数据库

  • Powermockito.mock():主要是经过class建立对应的mock对象,不一样于easymock等使用proxy(代理)的方式建立,而是在运行过程当中动态修改class字节码文件的形式来建立。
  • Do..when..then:能够按照英文的意思理解,就是在何时,作了什么事,而后怎么样了。
  • Verify:能够理解为验证无返回值时候,查看是否被调研。

进阶入门

接着我再来一个稍稍有点难度的需求,须要建立学生操做。api

须要在dao和service加入两个方法以下:单元测试

dao中加入:学习

    /**
     * create student
     *
     * @param student
     */
    public void createStudent(Student student) {
        throw new UnsupportedOperationException();
    }

service中加入:测试

    /**
     * create student
     * @param student
     */
    public void createStudent(Student student) {
        studentDao.createStudent(student);
    }

若是针对createStudent写单元测试,确定是错误的,很明显数据库资源不存在,上个案例已经说了,这里不作赘述,重点是此次是验证无返回值类型的测试,即void,那该怎么测试呢?spa

mock后的createStudent方法,实际什么都不会作,仔细想下,咱们调用createStudent方法,按照用例测试,也无非就是调用成功或者失败,可先假设调用成功或失败.。代理

而后,使用mock中verify这个方法便可完成验证,具体示例代码以下:code

@Test
    public void testCreateStudentWithMock() {
        StudentDao studentDao = PowerMockito.mock(StudentDao.class);
        Student student=new Student();
        PowerMockito.doNothing().when(studentDao).createStudent(student);
        StudentService studentService = new StudentService(studentDao);
        studentService.createStudent(student);
        Mockito.verify(studentDao).createStudent(student);
    }

再次运行就可以经过,其中Mockito.verify主要用来校验被mock出来的对象中的某个方法是否被调用。htm

到此关于mock的入门就结束了。

相关文章
相关标签/搜索