0

I have a method in my MainActivity and I want to mock the A instance :

public void some_method() {
    A a = new A(); 
    ....   
}

so I tried creating in the MainActivity class a method

public A createA(){return new A()}

and then some_method becomes

public void some_method() {
        A a = createA(); 
        ....   
    }

I tried this

    MainActivity mainActivitySpy = (MainActivity)Mockito.spy(MainActivity.class);
    when(mainActivity.createA()).thenReturn(null)

but I get this error message

org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.

Is there a way to mock the constructor ? I tried the a solution SO post (18 points at the time of the writing, solution without Poweermockito) but I was not able to make this work, because I don't think it is functional

user1611830
  • 4,749
  • 10
  • 52
  • 89

3 Answers3

0

Using Mockito you can not mock constuctor, but with PowerMockito you can.

Problem here is, your spy call has to be on actual instance. You cannot call it in a you call the mocking a class.

MainActivity activityInstance = <get your activity instance>;

MainActivity mainActivitySpy = Mockito.spy(activityInstance);
    when(mainActivity.createA()).thenReturn(null);
kuhajeyan
  • 10,727
  • 10
  • 46
  • 71
0

I would pass the mocked A object as an argument to some_method(). Also you could create a special factory for A objects then you could mock the factory

Buckstabue
  • 283
  • 1
  • 13
0

You are creating a spy for MainActivity called mainActivitySpy but you are calling the when on an object call mainActivity that I presume is not a mock nor a spy. Changing the when call gives the desired effect:

import static org.mockito.Mockito.*;

public class MainActivity {

    public A createA(){
        return new A();
    }

    public void some_method() {
        A a = createA(); 
        System.out.println("Mock:" + a);
    }

    public static void main(String[] args) {

        MainActivity mainActivitySpy = (MainActivity)spy(MainActivity.class);
        when(mainActivitySpy.createA()).thenReturn(null);

        mainActivitySpy.some_method();

    }
}
Gergely Toth
  • 6,638
  • 2
  • 38
  • 40