How to capture JMockit expectation for known argument but fail if method is called with different argument

StackOverflow https://stackoverflow.com/questions/21556431

Question

In JMockit how do you set an expectation for a method to be called 1 time for a known argument (or mocked argument) but set it to fail if it calls the method with a different argument.

i.e. I want to set an expectation for times = 1 where Arg = "XYZ" but times = 0 for any other call to method where Arg != "XYZ".

The ordering of these expectations only caused my test to fail. I did find a way to do this albeit to me it is rather cumbersome I feel, here is the code:

            obj.getDTOs(anyString);
            result = new Delegate() {
                    List<DTO> getDTOs(String testArg)
                    {
                        if (testArg.equals(expectedString)) {
                            return Collections.<DTO>emptyList();
                        } else {
                            throw new IllegalArgumentException();
                        }
                    }
            };
            result = Collections.<DTO>emptyList();
            times = 1;

Is this the best way?

Was it helpful?

Solution

The following will work, although it could also be done with a Delegate:

static class Service {
    List<?> getDTOs(String s) { return null; }
}

@Test
public void example(@Mocked final Service obj) {
    new NonStrictExpectations() {{
        obj.getDTOs("XYZ"); times = 1; // empty list is the default result
        obj.getDTOs(withNotEqual("XYZ")); times = 0;
    }};

    assertEquals(0, obj.getDTOs("XYZ").size());
    obj.getDTOs("abc"); // fails with "unexpected invocation"
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top