Mock of a class that has parameters in the constructor

Asked

Viewed 476 times

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 builder a jsonObject as a parameter. There’s no way to instantiate a mock class, so the when makes an exception. The test creates an instance of the class ParseProcesso (but obviously it doesn’t work)... Does anyone have any idea what to do?

  • You can’t use it new ParseProcesso(any());?

1 answer

0


1 - Use of @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;
  }

}

Testing:

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 method 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 - Refactoring your code for Factory usage (maybe that help you with some other idea).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.