使用Spring Boot 1.5避免Kafka Streams开始测试

ric*_*din 6 java spring-boot apache-kafka-streams spring-kafka spring-boot-test

Spring Boot应用程序的测试过程中,我遇到了一个非常烦人的问题.我有一个使用Kafka Streams的应用程序,并在专用配置文件中声明它们.

@EnableKafka
@EnableKafkaStreams
@Configuration
public class KafkaStreamConfiguration {
    @Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
    public StreamsConfig kStreamsConfigs() {
        // Omissis
    }
    @Bean
    public KStream<String, String> kStream() {
        // Omissis
    }
}
Run Code Online (Sandbox Code Playgroud)

我的应用程序还使用Spring公开了一个专用的REST API @RestController.我想隔离测试这个休息控制器,如下所示.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class RestControllerTest {
    @Test
    public void someFancyTest() {
        // Omissis
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是我无法避免Spring上下文启动KafkaStreamConfiguration类中定义的流.我没有找到任何方法在执行期间从Spring上下文中排除这个类RestControllerTest.

我不想KafkaEmbeddedRestControllerTest课堂上声明一个实例.在我看来这是胡说八道.

可能吗?如何切片测试以保持一定的独立性?

应用程序类尽可能简单.

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用的是Spring Boot 1.5.8和Kafka版本0.10.2.1.

Jam*_*mes 3

我为我的测试控制器构建测试,在其中显式定义配置类。这允许我根据需要混合真实配置和模拟配置。所以你应该能够模拟 Kafka 和其他你没有测试的东西。

这就是我注释测试类的方式:

@RunWith(SpringRunner.class)
@Import({
    MockIntegrationConfiguration.class,
    RealConfiguration.class,
})
@WebMvcTest(RestController.class)
public class RestControllerTest {
Run Code Online (Sandbox Code Playgroud)

我自动连接 MockMvc 来测试 API:

@Autowired
private MockMvc mockMvc;
Run Code Online (Sandbox Code Playgroud)