Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock constructor with mockito

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 error org.mockito.exceptions.misusing.InvalidUseOfMatchersException:

Any idea why?

like image 605
Mathew Rock Avatar asked Nov 29 '13 12:11

Mathew Rock


People also ask

How do you call a mock method in a constructor?

Faking static methods called in a constructor is possible like any other call. if your constructor is calling a method of its own class, you can fake the call using this API: // Create a mock for class MyClass (Foo is the method called in the constructor) Mock mock = MockManager. Mock<MyClass>(Constructor.

Is it possible to create a mock by calling one of its constructor True or false?

You can, but you probably don't want to: ComplexConstructor partialMock = Mockito. mock(ComplexConstructor. class, CALLS_REAL_METHODS);

How do you make a mock object?

Mock will be created by Mockito. Here we've added two mock method calls, add() and subtract(), to the mock object via when(). However during testing, we've called subtract() before calling add(). When we create a mock object using create(), the order of execution of the method does not matter.


1 Answers

You can use PowerMock to mock constructors.

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.

like image 165
Dave Avatar answered Oct 08 '22 23:10

Dave