Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To simulate a method invocation that is initiated by a method of a class, you can create a mock object of the class and then call the method on the mock object. This can be achieved by using a mocking framework such as Mockito or PowerMock, which allow you to create mock objects and specify the behavior of the mocked methods.

Here is an example using Mockito:

Suppose we have a class called Calculator with a method called add that takes two integers as parameters and returns their sum. We want to simulate the invocation of the add method to test another method that uses the Calculator class.

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

public class SomeClass {
    public int compute() {
        Calculator calculator = new Calculator();
        int result = calculator.add(2, 3);
        return result * 2;
    }
}

To simulate the invocation of the add method, we can create a mock object of the Calculator class and specify the behavior of the add method to return a fixed value. We can then call the compute method of SomeClass and verify that it returns the expected value.

import static org.mockito.Mockito.*;

public class SomeClassTest {
    @Test
    public void testCompute() {
        Calculator calculator = mock(Calculator.class);
        when(calculator.add(2, 3)).thenReturn(5);

        SomeClass someClass = new SomeClass();
        int result = someClass.compute();

        assertEquals(10, result);
    }
}

In this example, we create a mock object of the Calculator class using mock(Calculator.class). We then specify the behavior of the add method to return 5 when called with parameters 2 and 3 using when(calculator.add(2, 3)).thenReturn(5). Finally, we call the compute method of SomeClass and verify that it returns 10, which is the expected value computed as (2 + 3) * 2.