Mock of a class that has parameters in the constructor

1
public class ParseProcessoTest {
private final String PATTERN_DATA_HORA = "yyyy-MM-dd HH:mm:ss";
JSONObject jsonObject;

@Mock
ParseProcesso parseProcesso;

@Before
public void init(){
    jsonObject = new JSONObject("string qualquer");
    when(parseProcesso.movimentacaoTemAnexo(new JSONObject("outra string"))).thenReturn(false);
}

@Test
public void testaParse() throws IOException {
    ParseProcesso parseProcesso = new ParseProcesso(jsonObject);
    Processo processoTeste = parseProcesso.parse();

    //demais métodos

The class ParseProcesso receives in its constructor a jsonObject as parameter. There is no way to instantiate a mockada class, so when throws an exception. The test creates an instance of class ParseProcesso (but obviously it does not work) ... Does anyone have any idea what to do?

    
asked by anonymous 19.10.2017 / 13:38

1 answer

0

1 - Using @Spy / Mockito.spy ( )

Ex:

Constructor with parameter:

public class MyService {

  private String param;

  public MyService(String anyParam) {
    this.param = anyParam;
  }

  public String getParam() {
    return param;
  }

}

Test:

public class MyServiceTest {

  private String DEFAULT_STRING_VALUE = "any";

  @Test
  public void classInstanceShouldNotBeNull() {
    MyService service = Mockito.spy(new MyService("doesNotMatter"));
    Assert.assertNotNull(service);
  }

  @Test
  public void shouldReturnMyMockedString() {
    MyService service = Mockito.spy(new MyService("doesNotMatter"));
    Mockito.when(service.getParam()).thenReturn(DEFAULT_STRING_VALUE);
    Assert.assertEquals(DEFAULT_STRING_VALUE, service.getParam());
  }
}

2 - Using the Mockito extension of PowerMock

You could use the PoweMockito.whenNew () to return your mock every time a new instance of your class is created:

PowerMockito.whenNew(MyService.class).withArguments(Mockito.anyString()).thenReturn(myMock);

3 - Refactor your code to use Factory (maybe this help you with some other idea ).

    
19.10.2017 / 19:52