PowerMock学习(十一)之Mock private methods的使用

Mock  private methods

就是mock私有方法啦,学到这不难发现,我们其实大部分都是通过反射去完成单元测试的,但是在实际中,某个类中的私有方法,个人不建议使用反射来测试,因为有时候会覆盖单元测试中的方法,那么下面我们就来举个例子,来使用mock来模拟私有方法的测试。

模拟场景

假设我们按照人名去查找一个学生是否存在isExist(),如果存在就返回true,否则false,同时调用这个类中的私有的查找方法返回学生个数,如果存在返回1,不存在返回0

业务逻辑部分代码比较简单,具体代码如下:

package com.rongrong.powermock.mockprivate;

/**
 * @author rongrong
 * @version 1.0
 * @description:
 * @date 2019/12/5 21:48
 */
public class StudentPrivateService {

    public boolean isExist(String userName) {
        int count = checkExist(userName);
        if (count > 0) {
            return true;
        } else {
            throw new NullPointerException();
        }

    }

    private int checkExist(String userName) {
        throw new UnsupportedOperationException();
    }


}

接着我们是powermock进行测试,使用上一篇文章中所学的AnSwer和spy方法来进行测试。

具体代码如下:

package com.rongrong.powermock.mockprivate;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static junit.framework.TestCase.assertTrue;

/**
 * @author rongrong
 * @version 1.0
 * @description:
 * @date 2019/12/5 21:54
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(StudentPrivateService.class)
public class TestStudentPrivateService {

    @Test
    public void testStudentPrivateService(){
        StudentPrivateService studentPrivateService = PowerMockito.spy(new StudentPrivateService());
        try {
            PowerMockito.doAnswer(new Answer() {
                @Override
                public Integer answer(InvocationOnMock invocation) throws Throwable {
                    String arg= (String) invocation.getArguments()[0];
                    if("rongrong".equals(arg)){
                        return 1;
                    }else {
                        return 0;
                    }
                }
            }).when(studentPrivateService,"checkExist","rongrong");
            boolean exist = studentPrivateService.isExist("rongrong");
            assertTrue(exist);
            PowerMockito.verifyPrivate(studentPrivateService).invoke("checkExist","rongrong");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

到此,整个powermock的学习就完成了,不得不说,powermock比想象中的强大的多。

你可能感兴趣的:(PowerMock学习(十一)之Mock private methods的使用)