Ask Your Question
3

How can you simulate a method invocation that is initiated by a method of a class?

asked 2023-06-09 18:41:47 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-09 18:52:02 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-09 18:41:47 +0000

Seen: 22 times

Last updated: Jun 09 '23