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;
		});
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值