繁体   English   中英

使用 Mockito 2 模拟服务导致存根错误

[英]Simulation of Service using Mockito 2 leads to stubbing error

我尝试使用 Mockito 模拟类的行为。 这使用 Mockito 1.x 工作。 迁移到 JUnit 5 和 Mockito 2 似乎不再起作用了。

@ExtendWith(MockitoExtension.class)
public class MockitoExample {

  static abstract class TestClass {
    public abstract int booleanMethod(boolean arg);
  }

  @Mock
  TestClass testClass;

  @BeforeEach
  public void beforeEach() {
    when(testClass.booleanMethod(eq(true))).thenReturn(1);
    when(testClass.booleanMethod(eq(false))).thenReturn(2);
  }

  @Test
  public void test() {
    assertEquals(1,testClass.booleanMethod(true));
    assertEquals(2,testClass.booleanMethod(false));
  }
}

期望是,模拟的 TestClass 显示在测试方法中测试的行为。

我得到的错误是:

org.mockito.exceptions.misusing.PotentialStubbingProblem: 

  Strict stubbing argument mismatch. Please check:
   - this invocation of 'booleanMethod' method:
      testClass.booleanMethod(false);
      -> at org.oneandone.ejbcdiunit.mockito_example.MockitoExample.beforeEach(MockitoExample.java:30)
   - has following stubbing(s) with different arguments:
      1. testClass.booleanMethod(false);
        -> at org.oneandone.ejbcdiunit.mockito_example.MockitoExample.beforeEach(MockitoExample.java:29)
  Typically, stubbing argument mismatch indicates user mistake when writing tests.
  Mockito fails early so that you can debug potential problem easily.
  However, there are legit scenarios when this exception generates false negative signal:
    - stubbing the same method multiple times using 'given().will()' or 'when().then()' API
      Please use 'will().given()' or 'doReturn().when()' API for stubbing.
    - stubbed method is intentionally invoked with different arguments by code under test
      Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT).
  For more information see javadoc for PotentialStubbingProblem class.

在这两种情况下,参数false似乎都匹配,尽管我显然与true匹配。

这是 Mockito 2.17 中的错误还是误解。 我应该/如何使用 Mockito 2.x 来模拟​​具有不同布尔参数的调用?

示例也可以在 github 上找到。 但是surefire只会使用

mvn test -Dtest=MockitoExample

使用 Mockito 2.21 执行测试会得到相同的结果。

使用严格的存根(Mockito 的默认行为)在同一方法上调用多个when将重置该模拟。 解决方案是调用when once并在Answer有逻辑:

@BeforeEach
public void beforeEach() {
    when(testClass.booleanMethod(anyBoolean())).thenAnswer(invocationOnMock -> {
        if ((boolean) invocationOnMock.getArguments()[0]) {
            return 1;
        }
        return 2;
    });
}

或者,您可以使用 lenient mocking,但这并不总是一个好主意 - lenient mocking 允许冗余存根,并使您更容易在测试中犯错误,这可能会导致“生产”代码中未被注意的错误:

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public class MockitoExample {

从 Mockito 2.20 开始,也可以在本地添加 lenient()

@ExtendWith(MockitoExtension.class)
public class MockitoExample {

  static abstract class TestClass {
    public abstract int booleanMethod(boolean arg);
  }

  @Mock
  TestClass testClass;

  @BeforeEach
  public void beforeEach() {
    lenient().when(testClass.booleanMethod(eq(true))).thenReturn(1);
    lenient().when(testClass.booleanMethod(eq(false))).thenReturn(2);
  }

  @Test
  public void test() {
    assertEquals(1,testClass.booleanMethod(true));
    assertEquals(2,testClass.booleanMethod(false));
  }
}

Mockito 1 和 2 没有相同的“严格”级别。
除了将 Mockito 2 与 JUnit 4 或 5 一起使用外,默认级别仍然不同。

总结 :

3个级别的严格性:

  • LENIENT : 最低限度的严格
  • WARN : 向控制台发出的额外警告
  • STRICT_STUBS :通过在潜在误用时抛出异常来确保干净的测试,但也可能产生一些误报。

根据使用的 API 的默认有效级别:

  • Mockito 1 : LENIENT
  • 带有 JUnit 4 的 Mockito 2: WARN
  • 带有 JUnit 5 的 Mockito 2( MockitoExtension.class ): STRICT_STUBS
  • Mockito 3:计划成为STRICT_STUBS

更多细节

实际的 Mockito 文档对此非常清楚:

Strictness javadoc指出:

在模拟会话期间配置 Mockito 的“严格性”。会话通常映射到单个测试方法调用。 Strictness 驱动更干净的测试和更好的生产力。利用增强 Strictness 的最简单方法是使用 Mockito 的 JUnit 支持(MockitoRule 或 MockitoJUnitRunner)。如果您不能使用 JUnit 支持 MockitoSession 是要走的路。

严格程度如何影响测试的行为(模拟会话)?

1. Strictness.LENIENT - 无添加行为。Mockito 1.x 的默认值。仅当您不能使用 STRICT_STUBS 或 WARN 时才推荐。

2. Strictness.WARN - 有助于保持测试清洁并提高可调试性。报告有关未使用的存根和存根参数不匹配的控制台警告(请参阅 org.mockito.quality.MockitoHint)。使用 JUnitRule 或 MockitoJUnitRunner 时 Mockito 2.x 的默认行为。 如果您不能使用 STRICT_STUBS,则推荐使用。

3. Strictness.STRICT_STUBS - 确保干净的测试,减少测试代码重复,提高可调试性。灵活性和生产力的最佳组合。 强烈推荐。计划为 Mockito v3 的默认值。有关详细信息,请参阅 STRICT_STUBS。

但是无论抛出的与消息相关的异常

“具有以下不同参数的存根”

似乎是一个过于严格的检查。 异常消息在某种程度上证明了这一点:

但是,当此异常生成假阴性信号时,存在合法情况:

...

  • 被测试的代码故意使用不同的参数调用存根方法

所以默认禁止它似乎太多了。
因此,如果您使用 JUnit 5,作为STRICT_STUBS替代方案,您可以使用WARNING但您通常希望避免太安静的LENIENT

除了MockitoExtensionmockito-junit-jupiter库还提供了@MockitoSettings ,可以在方法级别和类级别使用。

这是一个例子:

import java.util.List;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;

@ExtendWith(MockitoExtension.class)
public class FooTest {

    @MockitoSettings(strictness = Strictness.WARN)
    @Test
    void foo() throws Exception {
        List<String> strings = Mockito.mock(List.class);
        Mockito.when(strings.add("a"))
               .thenReturn(true);
        Mockito.when(strings.add("b"))
               .thenReturn(false);
    }

    @Test
    void fooKo() throws Exception {
        List<String> strings = Mockito.mock(List.class);
        Mockito.when(strings.add("a"))
               .thenReturn(true);
        Mockito.when(strings.add("b"))
               .thenReturn(false);

    }

}

fooKo()foo()成功时抛出误用 Mockito 异常,但提供了有用的警告:

[MockitoHint] FooTest (see javadoc for MockitoHint):
[MockitoHint] 1. Unused -> at FooTest.foo(FooTest.java:19)
[MockitoHint] 2. Unused -> at FooTest.foo(FooTest.java:21)

作为另一种选择,您还可以使用Mockito.lenient()很好地描述的Mockito.lenient()来为特定调用应用宽松的严格性。 您还可以在模拟实例化时将每个模拟调用设置为宽松:

@Test
void foo() throws Exception {
    List<String> strings = Mockito.mock(List.class, Mockito.withSettings()
                                                           .lenient());
     ....
}

由于第一个答案出乎意料,我检查了以下内容:

interface Poops {
    String get(boolean is);
}

@Test
void test1() {
    Poops a = mock(Poops.class);

    when(a.get(eq(true))).thenReturn("1");
    when(a.get(eq(false))).thenReturn("2");

    Assertions.assertEquals("1", a.get(true));
    Assertions.assertEquals("2", a.get(false));
}

它适用于 Mockito 2.21.0。

更新:这个问题似乎是木星扩展的Mockito从而改变了默认设置Strictness.STRICT_STUBS

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM