7

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?

Yosi Dahari
  • 6,794
  • 5
  • 24
  • 44
Mathew Rock
  • 989
  • 2
  • 14
  • 32

4 Answers4

7

UPDATE: since since version 3.5.0, Mockito can do this without PowerMockito.

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.

tkruse
  • 10,222
  • 7
  • 53
  • 80
Dave
  • 4,282
  • 2
  • 19
  • 24
  • I tried whith org.powermock.api.mockito.PowerMockito.whenNewnew(GeneraIDParaEntidadCliente(String.class, Entidad.class).thenReturn(generaIdMock) But doesn´t work. Any idea why? – Mathew Rock Dec 02 '13 at 07:58
  • I'd have to see more of your code to know exactly what's wrong. Are you using @RunWith(PowerMockRunner.class) and @PrepareForTest on the test class? See [here](http://code.google.com/p/powermock/wiki/MockitoUsage13). – Dave Dec 03 '13 at 02:26
  • 1
    @RunWith(PowerMockRunner.class) and @PrepareForTest({GeneraIDParaEntidadCliente .class}) – Mathew Rock Dec 03 '13 at 12:53
0

There are a couple of ways of doing this, described in my article on the Mockito wiki

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
0

Copying answer from duplicate: Mockito can now mock constructors (since version 3.5.0) https://javadoc.io/static/org.mockito/mockito-core/3.5.13/org/mockito/Mockito.html#mocked_construction

try (MockedConstruction mocked = mockConstruction(Foo.class)) {
   Foo foo = new Foo();
   when(foo.method()).thenReturn("bar");
   assertEquals("bar", foo.method());
   verify(foo).method();
 }
tkruse
  • 10,222
  • 7
  • 53
  • 80
-1

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);
M2E67
  • 937
  • 7
  • 23