IllegalArgumentException:期望块内的条件语句无效

IllegalArgumentException: Invalid conditional statement inside expectation block

我在测试用例中编写的 Expectations 块有问题:

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;
      }
    };

测试用例崩溃:

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

就在这里:

if (!pWithRealData) {

这只是一个简单的 boolean,在这种情况下是 false

我完全不知道为什么 exception 会发生。 我已经使用 google 进行了搜索,但没有找到任何有用的信息。

你能帮帮我吗?

来自 1.14 版的 JMockit 发行说明:

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.

与此相关的 GitHub 个问题:

在一期中,他们声明:

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.

在 JMockit source 中,您可以看到哪些其他类型的条件和循环会抛出该异常。

简而言之,从 JMockit 1.14 开始,您将不允许在 Expectation 块中使用条件(例如 if 语句)和循环。