首页 > 解决方案 > Overriding spring @Configuration in an integration test

问题描述

I have a spring boot configuration class like this:

@Configuration
public class ClockConfiguration {

    @Bean
    public Clock getSystemClock() {
        return Clock.systemUTC();
    }
}

and I have some integration tests like this:

@SpringBootTest(classes = MyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public abstract class AbstractIntegrationTest  {

}

and tests like this:

public class MiscTests extends AbstractIntegrationTest{

    @Test
    public void CreateSomethingThatOnlyWorksInThe Morning_ExpectCorrectResponse() {

    }

I want to be able to offset the clock bean to run some tests at different times on the day. How do I do this?

NOTE: I see several stack overflow answers similar to this, but I can't get them to work.

Based on other responses, it appears the solution should be something like:

@SpringBootTest(classes = MyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public abstract class AbstractIntegrationTest  {

    @Configuration
    class MyTestConfiguration {

        @Bean
        public Clock getSystemClock() {
            Clock realClock = Clock.systemDefaultZone();
            return Clock.offset(realClock, Duration.ofHours(9));
        }
    }
}

But nothing happens there. Do I need to @Import something? do I need to @Autowired something?

Thanks!

标签: javaspring-bootintegration-testing

解决方案


当您使用 Spring Boot 时,您可以利用@MockBean注释:

@SpringBootTest(classes = MyApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public abstract class AbstractIntegrationTest  {

    @MockBean
    private Clock clockMock;
}

然后,您可以相应且唯一地存根该 bean 的公共方法和每个测试:

@Test
public void CreateSomethingThatOnlyWorksInThe Morning_ExpectCorrectResponse() {
     when(clockMock.getTime()).thenReturn(..);
}

根据 javadoc 的@MockBean

在上下文中定义的任何现有的相同类型的单个 bean 都将被模拟替换。


推荐阅读