如何使用mockito在私有方法中模拟声明的类

rbpvctlc  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(466)

我正在编写junit测试来测试在其中声明了类的私有方法。
我的代码:

  1. private Object getFunctReturn()
  2. {
  3. InterfaceName obj = new ClassName():
  4. Map map = obj.getMap();
  5. map.foreach()->{
  6. //iterating map here....
  7. }
  8. }

我正在使用whitebox api测试私有方法。如何模拟interfacename obj=new classname();这样我就可以继续执行下一个代码了?

e4eetjau

e4eetjau1#

试着这样做:

  1. @RunWith(PowerMockRunner.class)
  2. @PrepareForTest(ClassUnderTest.class)
  3. public class SimpleTest {
  4. @Test
  5. public void test() throws Exception {
  6. ClassUnderTest underTest = new ClassUnderTest();
  7. ClassName obj = new ClassName();
  8. obj.setMap(Map.of("1", "one", "2", "two"));
  9. PowerMockito.whenNew(ClassName.class).withNoArguments().thenReturn(obj);
  10. WhiteboxImpl.invokeMethod(underTest, "getFunctReturn");
  11. }
  12. }
展开查看全部

相关问题