本文介绍了如何在@SpringBootTest 中创建可重用的@MockBean 定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 @SpringBootTest 类,它有一个相当复杂的模拟定义设置,带有模拟返回值.

I have a @SpringBootTest class that has a rather complex mock definition setup with mocked return values.

问题:我可以将 @MockBean 设置外部化到一个自己的类中,以便我可以在多个类中重用模拟配置(旁注:我寻找继承在这里!).

Question: can I externalize @MockBean setups into an own class, so I could reuse the mock configuration in multiple class (sidenote: I'm not looking for inheritance here!).

@SpringBootTest
public class ServiceTest extends DefaultTest {
    @Autowired
    private ServiceController controller;

    @MockBean
    private Service1 s1;

    @MockBean
    private Service2 s2;

    @MockBean
    private Service3 s3;

    //assume more complex mock definitions
    @BeforeEach
    public void mock() {
        when(s1.invoke()).thenReturn(result1);
        when(s2.invoke()).thenReturn(result2);
        when(s3.invoke()).thenReturn(result3);
    }

    @Test
    public void test() {
        //...
    }
}

我想为我的所有测试独立加载模拟,而不是全局加载.

I want to load the mocks independently of each other, not globally for all my tests.

推荐答案

不是直接要求的,但一种可能性是不使用 @MockBean 而是将可重用的模拟定义为 @Primary @Bean 在多个 @TestConfiguration 中,您可以在测试中选择性地@Import:

Not directly what you are asking for, but one possibility is to not use @MockBean but instead define your reusable mocks as @Primary @Beans in multiple @TestConfigurations that you can selectively @Import in your tests:

@TestConfiguration
public class MockService1 {

  @Bean
  @Primary
  public Service1 service1Mock() {
    Service1 s1 = Mockito.mock(Service1.class);
    when(s1.invoke()).thenReturn("result1");
    return s1;
  }
}

有一篇关于这种方法的好文章:使用 Spring Boot 构建可重用的 Mock 模块.

There's a nice article about this approach: Building Reusable Mock Modules with Spring Boot.

这篇关于如何在@SpringBootTest 中创建可重用的@MockBean 定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-23 21:45