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

私有方法mock单元测试可以使用PowerMockito框架来实现。首先,需要在测试类上添加@PrepareForTest注解,注解中指定私有方法所在的类。然后,使用PowerMockito.spy()方法创建被测试类的一个spy对象。接下来,使用PowerMockito.when()方法mock私有方法的调用,并指定方法的参数和返回值。最后,在测试方法中调用被测试类的方法,即可触发mock私有方法的逻辑。 具体代码如下所示: ```java @PrepareForTest({YourClass.class}) public class YourClassTest { @Test public void testPrivateMethod() throws Exception { YourClass yourClass = PowerMockito.spy(new YourClass()); PowerMockito.when(yourClass, PowerMockito.method(YourClass.class, "privateMethod", ArgumentMatchers.anyString())) .thenReturn("mockedValue"); // 调用被测试类的方法,触发私有方法的逻辑 String result = yourClass.publicMethod(); // 验证结果 Assert.assertEquals("expectedValue", result); } } ``` 在上述代码中,我们使用PowerMockito.spy()方法创建了YourClass的一个spy对象,然后使用PowerMockito.when()方法mock私有方法privateMethod的调用,并指定方法的参数和返回值。最后,在测试方法中调用被测试类的publicMethod方法,即可触发mock私有方法的逻辑。最后,使用断言来验证结果是否符合预期。 需要注意的是,为了使用PowerMockito框架,需要在pom.xml文件中添加相应的依赖,如引用\[2\]所示。另外,还需要在测试类上添加@RunWith(PowerMockRunner.class)注解,以及@PrepareForTest注解,注解中指定私有方法所在的类。 希望对你有帮助! #### 引用[.reference_title] - *1* *2* *3* [junit单元测试mock私有private方法静态static方法](https://blog.csdn.net/lzxlfly/article/details/126911994)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值