以前从未见过此问题 - 当使用 verify
或 verifyInteractions
且测试失败时,Mockito 的调用列表指向 JUnit 代码而不是应用程序代码:
[junit] No interactions wanted here:
[junit] -> at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
[junit] But found this interaction on mock 'mockCounter':
[junit] -> at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
[junit] ***
[junit] For your reference, here is the list of all invocations ([?] - means unverified).
[junit] 1. [?]-> at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
[junit] 2. [?]-> at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
[junit] 3. -> at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
[junit]
[junit] junit.framework.AssertionFailedError:
[junit] No interactions wanted here:
[junit] But found this interaction on mock 'mockCounter':
[junit] ***
[junit] For your reference, here is the list of all invocations ([?] - means unverified).
我正在使用 Mockito 1.10.19
和 JUnit 4.12
。代码非常标准:
public class MyTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private Counter mockCounter;
...
@Test
public void test() {
...
verifyNoMoreInteractions(mockCounter);
}
首先,我还使用了 ExpectedException
规则:
@Rule
public ExpectedException thrown = ExpectedException.none();
...这导致了额外的问题,因为它捕获了 Mockito 的验证失败作为意外异常:
[junit] No interactions wanted here:
[junit] -> at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
[junit] But found this interaction on mock 'mockCounter':
[junit] -> at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
[junit] ***
[junit] For your reference, here is the list of all invocations ([?] - means unverified).
[junit] 1. [?]-> at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
[junit] 2. [?]-> at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
[junit] 3. -> at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
[junit]
[junit] junit.framework.AssertionFailedError:
[junit] No interactions wanted here:
[junit] But found this interaction on mock 'mockCounter':
[junit] ***
[junit] For your reference, here is the list of all invocations ([?] - means unverified).
我正在开发一个新的代码库,以前从未见过这个问题。似乎 Mockito 或 JUnit 清理堆栈跟踪过于积极或其他什么......
我可以在没有ExpectedException
的情况下生活,但是在未来测试失败的情况下没有模拟调用点似乎很烦人。我怎样才能解决这个问题?我saw withSettings().verboseLogging()
的概念,但我不想始终记录调用,只有在测试失败时才记录。
最佳答案
看来 MockitoRule
是罪魁祸首。在 setUp()
方法中用 MockitoAnnotations.initMocks(this);
替换它可以完全解决问题,即使使用 ExpectedException
规则也是如此。 p>
已经fixed在 Mockito 2.x
中,但未向后移植到 1.x
。
关于java - Mockito 模拟调用点指向 Junit 代码(ParentRunner),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59059398/