带有Mockito.mock的java Json.toJson =无限递归(StackOverflowError)

时间:2018-01-06 03:51:26

标签: java unit-testing mockito

我有一个来自第三方lib的课程,我们可以在详细课程中调用

在我的测试文件中,我有这样的代码:

<div class="main">
  <div>
    <div class="image">This should be visible</div>
  </div>
  <div class="text">This should be hidden</div>
  <div class="text">This should be hidden</div>
  <div>
    <div class="image">This should be hidden</div>
  </div>
</div>

在我的源代码中,我有

private Details details;
...
details = mock(Details.class);
//details = new Details(); // without mock, it works no error.
...
List<Details> DetailsList = new ArrayList<>();
DetailsList.add(details);
when(myPost.getDetails()).thenReturn(DetailsList);

问题是,如果我在单元测试中模拟我的课程,例如List<Details> details = myPost.getDetails(); details.forEach(detail -> { JsonNode detailJson = Json.toJson(detail); // this line throw error with when I use mock in unit test ... }) ,那么它会在这一行details = mock(Details.class);上给我以下错误

  

java.lang.RuntimeException:java.lang.IllegalArgumentException:无限   递归(StackOverflowError)(通过引用链:   org.mockito.internal.creation.bytebuddy.InterceptedInvocation [ “模拟”] - org.mockito.internal.creation.bytebuddy.MockMethodInterceptor [ “mockHandler”] - org.mockito.internal.handler.InvocationNotifierHandler [ “invocationContainer”])< / p>

但是,如果我不嘲笑它,并使用Json.toJson(detail)代替,则没有错误。

我在网上找到的信息说这个错误发生是因为类(例如:Detail)有循环引用。但是,我不认为是这种情况,因为没有在Detail类上使用mock,根本就没有问题。

只有当details = new Details();Json.toJson一起使用时,才会出现此错误。有没有遇到过这个问题?

0 个答案:

没有答案