javajunitjmockitillegalargumentexceptionexpectations

IllegalArgumentException: Invalid conditional statement inside expectation block


I have a problem with an Expectations block I have written in my test case:

new Expectations() {
      {
        mFindHandlerMock.findAll((Model) any, (Set<Id>) any, false);
        if (!pWithRealData) {
          result = Collections.emptySet();
        } else {
          result = pAllData;
        }
        times = 1;

        Deencapsulation.invoke(mDb, "readSqlQuery", withAny(String.class));
        result = "select * from realdata";
        times = 1;
      }
    };

the test case crashes with:

java.lang.IllegalArgumentException: Invalid conditional statement inside expectation block

exactly here:

if (!pWithRealData) {

it's just a simple boolean that is false in this case.

I have absolutly no clue why the exception happens. I already searched with google but found nothing helpful.

Could you help me?


Solution

  • From the JMockit release notes for version 1.14:

    Enhancement: Conditionals and loops will now trigger an exception when found inside an expectation recording block, to prevent API misuse and to encourage simpler tests. See issue #97.

    The GitHub issues related to this:

    In the one issue they state that:

    Yes, and this is as intended, to avoid tests getting too complicated when recording expectations. A full test was not shown, but it looks to me that recording the specific expectations directly would be better in this case.

    In the JMockit source you can see which other types of conditionals and loops will throw that exception.

    In short, from JMockit 1.14 onwards you are not allowed to have conditionals (such as if statements) and loops in the Expectation block.