• PowerMock学习(二)之PoweMock的入门


    前言

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

    Mock中的API

    ps:仅更新这次案例中使用的api说明。

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

    进阶入门

    接着我再来一个稍稍有点难度的需求,需要创建学生操作。

    需要在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,那该怎么测试呢?

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

    然后,使用mock中verify这个方法即可完成验证,具体示例代码如下:

    @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出来的对象中的某个方法是否被调用。

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

  • 相关阅读:
    (OK) CORE nodes access Internet—虚拟节点访问互联网—commands
    Open VSwitch—离开VMware的SDN之父Martin Casado是神马大神
    (OK-half) Fedora23——Docker——CORE—testing
    【codeforces 752B】Santa Claus and Keyboard Check
    【codeforces 752C】Santa Claus and Robot
    【codeforces 752E】Santa Claus and Tangerines
    【codeforces 548E】Mike and Foam
    【codeforces 752D】Santa Claus and a Palindrome
    【codeforces 752F】Santa Clauses and a Soccer Championship
    【codeforces 546A】Soldier and Bananas
  • 原文地址:https://www.cnblogs.com/longronglang/p/11894911.html
Copyright © 2020-2023  润新知