使用 mockito 模拟构造函数

2022-01-14 00:00:00 mockito java junit

我想将构造函数模拟为方法.

I want to mock a constructor into method.

public String generaID() {   
    GeneraIDParaEntidadCliente aux = new GeneraIDParaEntidadCliente(nombre, registro);   
    entidad.setID(aux.generaID);   
}

在我的测试中,我想做这样的事情:

In my test I want do something like this :

when(new GeneraIDParaEntidadCliente(anyString(), any(Entidad.class)).thenReturn(generaIdMock)  

但是给我这个error org.mockito.exceptions.misusing.InvalidUseOfMatchersException:

知道为什么吗?

推荐答案

可以使用 PowerMock 来模拟构造函数.

You can use PowerMock to mock constructors.

如果由于某种原因不能使用 PowerMock,最可行的解决方案是将工厂注入到包含此方法的任何类.然后,您将使用工厂创建您的 GeneraIDParaEntidadCliente 对象并模拟工厂.

If you can't use PowerMock for some reason, the most workable solution is to inject a factory to whatever class contains this method. You would then use the factory to create your GeneraIDParaEntidadCliente object and mock the factory.

相关文章