如何使用junit Mockito编写具有多个私有方法的void方法的单元测试

ryevplcw  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(148)

我试图测试一个有多个private方法的void方法,我采取的方法是,试图测试一个public方法,下面是public方法,

class Container{ 

public void checkAndUpdate(Service service, Actual actual){
 List<Address> addList = new ArrayList<>();
 for(Address addr: service.getAddress()){
  addList.add(addr);
}
somePrivateMethod(addList);
}

测试类

@Mock
Container container;

@Test
public void testCheckAndUpdate(){
 
List<Address> addList = Mockito.mock(List.class);
Service service = Mockito.mock(Service.class);
Actual actual = new Actual();
actual.setValue("TA");
service.setAddress(addList);

Mockito.verify(container).checkAndUpdate(service,actual);

我得到下面的例外

"Actually there were zero interactions with the mock 
    wanted but not invoked

如何解决这个问题

vom3gejh

vom3gejh1#

为了验证与私有方法的交互(如果您真的想这么做的话),它的可见性应该增加到包私有的可见性。
则可以使用以下方法

class ContainerTest {
    @Test
    void testCheckAndUpdate() {

        List<Address> addList = new ArrayList<>();
        Service service = Mockito.mock(Service.class);
        Actual actual = new Actual();
        actual.setValue("TA");
        service.setAddress(addList);

        Container container = Mockito.spy(new Container());
        // call the public method
        container.checkAndUpdate(service, actual);

        // verify interaction with the package-private method
        Mockito.verify(container).somePrivateMethod(addList);
    }
}

相关问题