繁体   English   中英

将bean注入到WebMvc测试的上下文中:@AutoConfigureMockMvc不能与@Component注解@Configuration结合使用

[英]Injecting a bean into the context of a WebMvc test: @AutoConfigureMockMvc cannot be used in combination with the @Component annotation @Configuration

对于我的 Java Spring 测试,我决定伪造系统时钟以使测试更容易

我有一个继承公共基类的测试 bean

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc(print = MockMvcPrint.LOG_DEBUG)
@TestExecutionListeners(mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS,
        value = {FlywayTestExecutionListener.class}
)
@FlywayTest
@Getter(AccessLevel.PROTECTED)
public abstract class AbstractMockMvcTest {}


@Configuration
@Sql(scripts = "classpath:..", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "classpath:..", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@WithMockUser(username = "junit", authorities = {}, roles = {})
class RolesControllerTest extends AbstractMockMvcTest {

    private final Instant fixedInstant = Instant.from(OffsetDateTime.of(2021, 6, 2, 15, 54, 0, 0, ZoneOffset.ofHours(2)));

    @Bean
    Clock fakeClock() {
        return Clock.fixed(fixedInstant, ZoneId.ofOffset("UTC", ZoneOffset.ofHours(2)));
    }

}


@SpringBootApplication
public class Application {

   
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }


    @ConditionalOnMissingBean(Clock.class)
    @Bean
    public Clock systemClock() {
        return Clock.systemUTC();
    }
}

这个想法是我的应用程序声明了一个主时钟,每个需要访问时间的 bean 都使用它(例如getClock().instant()Instant.now(getClock()) )。 通过模拟时钟,我使测试更容易。

但是我发现使用 Spring bean 比使用 Mockito 更自然。 Java Clock具有正确模拟时钟的方法

应用程序的最佳实践是将 Clock 传递给任何需要当前时刻的方法。 依赖注入框架是实现这一目标的一种方式:

public class MyBean {
    private Clock clock;  // dependency inject
    ...
    public void process(LocalDate eventDate) {
      if (eventDate.isBefore(LocalDate.now(clock)) {
        ...
      }
    }
  }
 

这种方法允许在测试期间使用备用时钟,例如固定或偏移。

但是当我尝试运行测试时,我偶然发现了这个

@AutoConfigureMockMvc cannot be used in combination with the @Component annotation @Configuration

在 Web MVC 测试中声明额外的主要 bean 有什么聪明的想法吗?

设置一个静态内部@TestConfiguration类,其中定义了 bean:

// Remove the @Configuration annotation here
@Sql(scripts = "classpath:..", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "classpath:..", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@WithMockUser(username = "junit", authorities = {}, roles = {})
@ContextConfiguration(classes = RolesControllerTest.TestConfiguration.class) // Add a ContextConfiguration if the test configuration isn't automatically used.
class RolesControllerTest extends AbstractMockMvcTest {

    private final Instant fixedInstant = Instant.from(OffsetDateTime.of(2021, 6, 2, 15, 54, 0, 0, ZoneOffset.ofHours(2)));

    @TestConfiguration
    public static class TestConfig {

        @Bean
        Clock fakeClock() {
            return Clock.fixed(fixedInstant, ZoneId.ofOffset("UTC", ZoneOffset.ofHours(2)));
        }
    }
}

另一种方法是声明一个@MockBean private Clock clock并使用 mockito 返回固定时刻。

我发现以下工作。 这是@Michiel 的一个稍微替代的解决方案。 最初(并且在发布答案之前)我尝试了他们的内部配置类方法,但我偶然发现了另一个问题:内部配置类, @Configuration @TestConfiguration@TestConfiguration删除了整个上下文,并且没有其他 bean 可见。 包括无法自动装配的PlatformTransactionManager

以下对我有用

@Configuration
@Sql(scripts = "classpath:..", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "classpath:..", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@WithMockUser(username = "junit", authorities = {}, roles = {})
class RolesControllerTest extends AbstractMockMvcTest {

    private final Instant fixedInstant = Instant.from(OffsetDateTime.of(2021, 6, 2, 15, 54, 0, 0, ZoneOffset.ofHours(2)));

    @TestConfiguration
    @Import(Application.class)
    static class ClockConfigurer {
        @Bean
        @Primary
        Clock fakeClock() {
            return Clock.fixed(fixedInstant, ZoneId.ofOffset("UTC", ZoneOffset.ofHours(2)));
        }
    }

}

就我而言,我必须@Import注释添加到测试配置类,指向主配置。

我最初在测试类中使用@Import ,将其注释掉,但每次上下文出错时。 我还必须将时钟标记为@Primary才能使用自动装配的按类型分辨率

这有帮助。 仍然感谢@Michiel

暂无
暂无

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

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