首页 > 解决方案 > Spring Boot 测试中的严格@MockBean

问题描述

我正在开发一个 Spring Boot 应用程序。对于我的常规服务类单元测试,我可以使用 扩展我的测试类MockitoExtension,并且模拟是严格的,这就是我想要的。

interface MyDependency {
  Integer execute(String param);
}

class MyService {
  @Autowired MyDependency myDependency;

  Integer execute(String param) {
    return myDependency.execute(param);
  }
} 

@ExtendWith(MockitoExtension.class)
class MyServiceTest {
  @Mock
  MyDependency myDependency;

  @InjectMocks
  MyService myService;

  @Test
  void execute() {
    given(myDependency.execute("arg0")).willReturn(4);
    
    myService.execute("arg1"); //will throw exception
  }
}

在这种情况下,将引发异常并显示以下消息(已编辑):

org.mockito.exceptions.misusing.PotentialStubbingProblem: 
Strict stubbing argument mismatch. Please check:
 - this invocation of 'execute' method:
    myDependency.execute(arg1);
 - has following stubbing(s) with different arguments:
    1. myDependency.execute(arg0);

此外,如果从未使用过存根,则会出现以下内容(已编辑):

org.mockito.exceptions.misusing.UnnecessaryStubbingException: 
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):
  1. -> at MyServiceTest.execute()

但是,当我@MockBean在集成测试中使用时,不存在任何严格的行为。相反,存根方法返回 null 因为存根“失败”静默。这是我不想要的行为。当使用意外的参数时,最好立即失败。

@SpringBootTest
class MyServiceTest {
  @MockBean
  MyDependency myDependency;

  @Autowired
  MyService myService;

  @Test
  void execute() {
    given(myDependency.execute("arg0")).willReturn(4);
    
    myService.execute("arg1"); //will return null
  }
}

有什么解决方法吗?

标签: javaspring-bootmockitospring-boot-test

解决方案


推荐阅读