如何修复`UnfinishedStubbingException`?

时间:2018-11-07 22:20:58

标签: mockito

我有以下内容:

public class EnvWebEndpointExtensionEnvironmentPostProcessorTests {
  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @Rule
  public MockitoRule rule = MockitoJUnit.rule();

  final EnvWebEndpointExtensionEnvironmentPostProcessor postProcessor = new EnvWebEndpointExtensionEnvironmentPostProcessor();

  @Mock
  ConfigurableEnvironment environmentMock;

  @Mock
  MutablePropertySources propertySourcesMock;

  @Test
  public void shouldAddPropertySource() {
    final MutablePropertySources propertySources = new MutablePropertySources();

    doReturn(propertySources) // line 40
        .when(environmentMock).getPropertySources();

    postProcessor.postProcessEnvironment(environmentMock, null);

    assertNotNull(propertySources.get("actuators-defaults"));
  }

  @Test
  public void shouldThrowExceptionOnFailingToAddLaptopPropertySource() {
    thrown.expect(RuntimeException.class);

    final MutablePropertySources propertySourcesReal = new MutablePropertySources();

    doReturn(propertySourcesReal)
        .when(environmentMock).getPropertySources();

    doReturn(true)
        .when(environmentMock).acceptsProfiles("laptop");
    doReturn(propertySourcesMock)
        .when(environmentMock).getPropertySources();
    doThrow(IOException.class) // line 61
        .when(propertySourcesMock).addBefore("actuators-defaults", any(ResourcePropertySource.class));

    postProcessor.postProcessEnvironment(environmentMock, null);
  }
}

分别运行测试时,它们会通过,但同时运行时,shouldAddPropertySource会失败,并显示:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at com.netflix.springboot.actuators.EnvWebEndpointExtensionEnvironmentPostProcessorTests.shouldThrowExceptionOnFailingToAddLaptopPropertySource(EnvWebEndpointExtensionEnvironmentPostProcessorTests.java:61)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, which is not supported
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed


    at com.netflix.springboot.actuators.EnvWebEndpointExtensionEnvironmentPostProcessorTests.shouldAddPropertySource(EnvWebEndpointExtensionEnvironmentPostProcessorTests.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.mockito.internal.junit.JUnitRule$1.evaluateSafely(JUnitRule.java:52)
    at org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:43)
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

考虑到我发现的信息和上述行为,Mockito正在存储一些静态状态,但是我的理解水平还不足以解决上述问题。正确的解决方法是什么,此外,此修复方法的解释是什么?

2 个答案:

答案 0 :(得分:1)

如果将匹配器用作存根方法调用的参数,则所有参数都必须是匹配器。因此,您需要将"actuators-defaults"替换为eq("actuators-defaults")

我不确定为什么会引发该异常。

答案 1 :(得分:0)

JB Nizet正确诊断了his answer中的根本原因:当对一个参数使用匹配器时,必须对所有参数使用匹配器。

我的直觉是Mockito正确地抛出了InvalidUseOfMatchersException,它源自RuntimeException,因此您的测试错误地通过了而没有执行被测系统。这是一个重要的原因,不能不加选择地捕获RuntimeException,尤其是在测试方法的顶部。这也可能是使用assertThrowstry { methodUnderTest(); fail(); } catch (YourSpecificException expected) {}习惯用法的原因。

如果是这种情况,您会看到该特定异常,因为测试运行程序正在同一VM上以shouldThrowshouldAdd的顺序调用测试,而Mockito将其匹配器状态保持在{{ 3}}可能在两次测试之间仍然存在。如果该理论是正确的,则在Mockito可以存储第61行的期望之前发生InvalidUseOfMatchersException,从而使第61行的存根在技术上未完成。由于Mockito不知道一个测试何时结束而另一个测试何时开始,因此无法重置其状态,因此Mockito仅在下次与Mockito交互时(第40行)才能检测到这种情况。

您可以通过在@After方法中调用static ThreadLocal(或使用Mockito.validateMockitoUsage()MockitoRule)来改善体验。