alexD
alexD

Reputation: 2364

How do I return multiple values from mocked method for different cases?

    new MockUp<SomeClass>() {
        @Mock
        boolean getValue() {
            return true;
        }
    };

I want to return a different value from getValue() depending on the test case. How can I do this?

Upvotes: 2

Views: 1303

Answers (1)

Rog&#233;rio
Rog&#233;rio

Reputation: 16380

To have different behavior from the same mocked class in different tests, you need to specify the desired behavior in each separate test. For example, in this case:

public class MyTest
{
    @Test public void testUsingAMockUp()
    {
        new MockUp<SomeClass>() { @Mock boolean getValue() { return true; } };

        // Call code under test which then calls SomeClass#getValue().
    }

    @Test public void anotherTestUsingAMockUp()
    {
        new MockUp<SomeClass>() { @Mock boolean getValue() { return false; } };

        // Call code under test which then calls SomeClass#getValue().
    }

    @Test public void testUsingExpectations(@NonStrict final SomeClass mock)
    {
        new Expectations() {{ mock.getValue(); result = true; }};

        // Call code under test which then calls SomeClass#getValue().
    }

    @Test public void anotherTestUsingExpectations(
        @NonStrict final SomeClass mock)
    {
        // Not really needed because 'false' is the default for a boolean:
        new Expectations() {{ mock.getValue(); result = false; }};

        // Call code under test which then calls SomeClass#getValue().
    }
}

You can instead create reusable MockUp and Expectations subclasses, of course, but they would also be instantiated in each test which needs the specific behavior.

Upvotes: 3

Related Questions