且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在应用程序启动之前配置@MockBean组件

更新时间:2023-12-04 09:56:46

在这种情况下,您需要采用引入@MockBean之前所用的方式配置模拟-通过手动指定一个@Primary bean在上下文中替换原始的.

In this case you need to configure mocks in a way we used to do it before @MockBean was introduced - by specifying manually a @Primary bean that will replace the original one in the context.

@SpringBootTest
class DemoApplicationTests {

    @TestConfiguration
    public static class TestConfig {

        @Bean
        @Primary
        public SystemTypeDetector mockSystemTypeDetector() {
            SystemTypeDetector std = mock(SystemTypeDetector.class);
            when(std.getSystemType()).thenReturn(TYPE_C);
            return std;
        }

    }

    @Autowired
    private SystemTypeDetector systemTypeDetector;

    @Test
    void contextLoads() {
        assertThat(systemTypeDetector.getSystemType()).isEqualTo(TYPE_C);
    }
}

由于@TestConfiguration类是静态内部类,因此仅此测试会自动选择它.您将要放入@Before中的完整模拟行为必须移至用于初始化bean的方法.

Since @TestConfiguration class is a static inner class it will be picked automatically only by this test. Complete mock behaviour that you would put into @Before has to be moved to method that initialises a bean.