Mock of a class that has parameters in the constructor

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

ParseProcesso parseProcesso;

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

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


1 - Using @Spy / Mockito.spy ( )


Constructor with parameter:

public class MyService {

  private String param;

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

  public String getParam() {
    return param;



public class MyServiceTest {

  private String DEFAULT_STRING_VALUE = "any";

  public void classInstanceShouldNotBeNull() {
    MyService service = Mockito.spy(new MyService("doesNotMatter"));

  public void shouldReturnMyMockedString() {
    MyService service = Mockito.spy(new MyService("doesNotMatter"));
    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:


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

19.10.2017 / 19:52