Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JMockIt: Is it possible to mock same class twice, in the same TestClass, to verify behaviour in different scenarios

I need to write a test, where-in, the behaviour of a class can be verified, for different behaviours of a Mocked class. To support multiple behaviours for the same method, we need to mock the class multiple times, in the same TestClass.

Is it possible using JMockIt?

Here is an example of what I want. This is the main class to be tested and its test:

public class MyClass {

    private Foo fooObj = null;

    public setfooObj(Foo obj) {
        fooObj = obj;
    }

    public boolean process() {
        // uses fooObj.getName() to process 
    }
}

public class MyClassTest {

    @MockClass(realClass = mypackage.Foo.class)
    public static class MockFoo {

        @Mock
        public static boolean getName() {
            return "test";
        }
    }

    @Test
    public void validateProcessing() {
        MyClass testObj = new MyClass();
        assertEquals(false, testObj.process);
    }
}

Now, I want to verify testObj.process() method's behaviour, when MockFoo.getName() returns different values. For my first assertion, I want to use its value as "test"(as returned by the mocked function), but for the following ones, I want to check with different values.

like image 426
neha1395049 Avatar asked Nov 02 '25 06:11

neha1395049


1 Answers

This is easy to solve, and there is no need to mock the same class twice. To return different values from the same mocked method in different invocations, simply record two (or more) consecutive return values if using the "Expectations API"; if using the "Mockups API", add a first parameter of type "Invocation inv" to your mock method and then use "inv.getInvocationIndex()" to know which value should be returned (not as nice as the other option, but works fine).

For more documentation and examples, have a look at the JMockit project site, or under the "jmockit/www" dir in the full distribution.

like image 188
Rogério Avatar answered Nov 04 '25 03:11

Rogério



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!