Search code examples
androidkotlinmockingmockitoandroid-testing

How to override/customise the behaviour of a function using Mokito in Android


I am developing an Android project using Kotlin. I am also adding instrumentation tests into my project. This is my first time writing the Android instrumentation tests and I am struggling a bit. I am trying to mock the behaviour of a function using Mokito.

See this code snippet:

    //Create a mock object of the class Calculator
    Calculator mockCalculator = Mockito.mock(Calculator.class);
    //Return the value of 30 when the add method is called with the arguments 10 and 20
    Mockito.when(mockCalculator.add(10, 20)).thenReturn(30);

As you can see when add method is called it is returning 30. What I want to do is adding an extra step.

Something like this

Mockito.when(mockCalculator.add(10, 20)).
doThis(() -> {
   StaticApplicationClass.StaticProperty = 30; // please pay attention to this made up function
})
.thenReturn(30);

The above code is the made-up code. See the comment; is it possible to do that?


Solution

  • You can use thenAnswer() because it'll help you to do actions based on the values passed to the mock. In following case, I use getArgument() method to get passed arguments. Then I sum them and make StaticApplicationClass.StaticProperty to be equal to that sum. Then I return sum.

    Mockito.when(mockCalculator.add(any(Integer.class), any(Integer.class))).thenAnswer(i -> {
        int number1 = i.getArgument(0);
        int number2 = i.getArgument(1);
        int sum = number1 + number2;
        StaticApplicationClass.StaticProperty = sum;
        return sum;
    });