0


junit单元测试mock私有private方法和静态static方法

我们知道org.mockito.Mockito功能有限,不能mock 私有private、受保护的protected方法

org.powermock.api.mockito.PowerMockito更强大,支持对private和protected和static方法的mock

别忘记,首先要引入maven依赖

      <dependency>
          <groupId>org.powermock</groupId>
          <artifactId>powermock-module-junit4</artifactId>
          <version>2.0.9</version>
          <scope>test</scope>
      </dependency>

      <dependency>
          <groupId>org.powermock</groupId>
          <artifactId>powermock-api-mockito2</artifactId>
          <version>2.0.9</version>
          <scope>test</scope>
      </dependency>

一、mock private方法

有如下私有方法需要mock

    private MessageBo executeExpression(List<Executor> ruleList, Map<String, Object> replaceMap) {
        MessageBo messageBo = new MessageBo();
        messageBo.setFlag(Boolean.TRUE);
        for (Executor rule : ruleList) {
            Bindings bidBindings = getParamValueList(replaceMap, rule.getParam());
            Bindings ret = executeExpression(rule.getCompiledScript(), bidBindings);
            if (Boolean.FALSE.equals(ret.get("0"))) {
                messageBo.setCode((String)ret.get("1"));
                messageBo.setMsg((String)ret.get("2"));
                messageBo.setFlag(Boolean.FALSE);
                break;
            }
        }
        return messageBo;
    }

这时候可以利用PowerMockito的spy方法mock出方法所在的对象,然后利用PowerMockito的when(Object instance, String methodName, Object... arguments),调用方法并传递参数,thenAnswer(Answer<?> answer) mock期望的返回结果

具体代码如下:

public class MockTest extends BaseTests {

    @Test
    public void test() {
        GeneralValidateStrategyImpl generalValidateStrategy = PowerMockito.spy(new GeneralValidateStrategyImpl());
        List<Executor> ruleList = new ArrayList<>();
        Map<String, Object> replaceMap = new HashMap<String, Object>();
        try {
            PowerMockito.when(generalValidateStrategy,"executeExpression",ruleList, replaceMap).thenAnswer((m) -> {
                MessageBo messageBo = new MessageBo();
                messageBo.setFlag(Boolean.TRUE);
                return messageBo;
            });
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

二、mock静态方法

如有如下静态方法getCurrentUser

public class LoginContext {

    public static User getCurrentUser() {
        LoginContext loginContext = get();
        if (loginContext == null) {
            return null;
        }
        return loginContext.getUser();
    }
}

mock如下 ,注意需要再测试类加上@PrepareForTest({LoginContext.class}),注解@PrepareForTest里写的类是静态方法所在的类。

@PrepareForTest({LoginContext.class})
public class MyUserTest extends BaseTest {        
        PowerMockito.mockStatic(LoginContext.class);
        PowerMockito.when(LoginContext.getCurrentUser()).thenAnswer((m) -> {
            User user = new User();
            user.setUserName("xxx");
            return user;
        });
}

本文转载自: https://blog.csdn.net/lzxlfly/article/details/126911994
版权归原作者 Relian哈哈 所有, 如有侵权,请联系我们删除。

“junit单元测试mock私有private方法和静态static方法”的评论:

还没有评论