java junit 私有方法_使用junit测试静态私有方法

2015-03-30 06:30:01

阅读( 406 )

测试目标类如下:

package cn.outofmemory.junit;

public class TestTarget {

/**

* 移除正则表达式中需要转义的字符

* @param w word

* @return 移除正则表达式中需要转义的字符

* @author yukaizhao

* @date 2013-2-19

*/

private static String convert4Regex(String w) {

if (w == null) {

return null;

}

String[] convertedChars = {"\\",".","+","*","(",")","{","}","[","]","?","/","^","$","|"};

for (String c : convertedChars) {

w = w.replace(c, "\\" + c);

}

return w;

}

}

测试方法:

@Test

public void testConvert4Regex() throws Exception {

String input = "A+";

String expected = "A\\+";

Method targetMethod = TestTarget.class.getDeclaredMethod("convert4Regex", String.class);

targetMethod.setAccessible(true);

Object actual = targetMethod.invoke(TestTarget.class, new Object[]{input});

assertEquals(expected,actual);

}

分享给朋友:

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息:

面试题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
私有方法的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 ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值