模拟一个从构造函数调用的void方法

问题描述 投票:1回答:1

我正在测试以下课程。我需要从构造函数中模拟方法调用estabilishConnection,该方法将返回void。

 public class ClassToBeTested {



    private ClassToBeMocked classToBeMocked;
    private String name;
    private int age;

    ClassToBeTested(ClassToBeMocked classToBeMocked, String name){
      this.classToBeMocked = classToBeMocked;
      this.name = name;
      age = this.getAge(name);
      this.estabilishConnection();
    }

    private int getAge(String name){
      int age =  (int) classToBeMocked.getNameAgeMap().get(name);
      return age;
    }

    private void estabilishConnection(){
            ``````````````````````````
            ````````````````````````
     }


} 

下面是我尝试过的方法。但它不起作用

    @Test
    public void testMethodInClassToBeMocked(){
      ClassToBeMocked mockApp = Mockito.mock(ClassToBeMocked.class);
      HashMap testMap= new HashMap();
      testMap.put("xys", 11);
      Mockito.when(mockApp.getNameAgeMap()).thenReturn(testMap);
      ///PowerMockito for mocking the void method

        PowerMockito.spy(ClassToBeTested.class);
        PowerMockito.doNothing().when(ClassToBeTested.class, "estabilishConnection");

      ClassToBeTested classTest = new ClassToBeTested(mockApp, "xys");

      //Assertion of method in the test class goes here
    }

如何使estabiishConnection方法什么也不做?

junit mocking mockito powermock
1个回答
1
投票

PowerMockito.stub(PowerMockito.method(ClassToBeTested.class,“ estabilishConnection”))。toReturn(“ nothing”);

这个解决了这个问题

© www.soinside.com 2019 - 2024. All rights reserved.