Java 使用 mockito 模拟构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20286020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mock constructor with mockito
提问by Mathew Rock
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)
but give me this errororg.mockito.exceptions.misusing.InvalidUseOfMatchersException:
但给我这个错误org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Any idea why?
知道为什么吗?
采纳答案by Dave
You can use PowerMockto mock constructors.
您可以使用PowerMock来模拟构造函数。
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.
如果由于某种原因不能使用 PowerMock,最可行的解决方案是将工厂注入包含此方法的任何类。然后您将使用工厂来创建您的GeneraIDParaEntidadCliente
对象并模拟工厂。
回答by Dawood ibn Kareem
There are a couple of ways of doing this, described in my article on the Mockito wiki
有几种方法可以做到这一点,在我在 Mockito wiki 上的文章中有所描述
回答by M2E67
you can send mocked objects as paramemters to your class constructor, form example:
您可以将模拟对象作为参数发送到类构造函数,例如:
// define you object
public MainClassObj instanceClass;
// mock input parameter
MYClassObj mockedObj = Mockito.mock(MYClassObj.class);
// call construvtor with mocked parameter
instanceClass = new instanceClass(mockedObj);