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,604
  • 5
  • 22
  • 42
Mathew Rock
  • 989
  • 2
  • 15
  • 31

3 Answers3

8

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.

Berik
  • 7,551
  • 2
  • 30
  • 39
Dave
  • 4,246
  • 2
  • 17
  • 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
  • 73,541
  • 13
  • 95
  • 104
-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
  • 899
  • 7
  • 23