Comments (7)
Here's one solution...
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.kafka.core;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.Ordered;
import org.springframework.kafka.test.rule.KafkaEmbedded;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.TestExecutionListeners.MergeMode;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AbstractTestExecutionListener;
/**
* @author Gary Russell
* @since 1.0
*
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners(mergeMode = MergeMode.MERGE_WITH_DEFAULTS,
listeners = SpringWithEmbeddedTests.KafkaEmbeddedTestExecutionListener.class)
public class SpringWithEmbeddedTests {
private static final String KAFKA_BROKER_ADDRESSES = "kafka.broker.addresses";
@ClassRule
public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, "foo");
@Autowired
private ConsumerFactory<?, ?> consumerFactory;
@Test
public void test() {
DirectFieldAccessor accessor = new DirectFieldAccessor(this.consumerFactory);
@SuppressWarnings("unchecked")
Map<String, Object> configs = (Map<String, Object>) accessor.getPropertyValue("configs");
assertThat(configs.get("bootstrap.servers")).isEqualTo(embeddedKafka.getBrokersAsString());
}
public static class KafkaEmbeddedTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
System.setProperty(KAFKA_BROKER_ADDRESSES, embeddedKafka.getBrokersAsString());
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
@Configuration
public static class Config {
@Value("${" + KAFKA_BROKER_ADDRESSES + "}")
private String brokers;
@Bean
public static PropertySourcesPlaceholderConfigurer configurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public ConsumerFactory<String, String> consumerFactory() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);
// ...
return new DefaultKafkaConsumerFactory<>(props);
}
}
}
from spring-kafka.
Using a fixed port is probably ok locally but could be a problem on a CI build server.
from spring-kafka.
M-m-m. The sample from existing test-case:
@ClassRule
public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, ...);
...
@Bean
public Map<String, Object> consumerConfigs() {
Map<String, Object> consumerProps = KafkaTestUtils.consumerProps("testAnnot", "true", embeddedKafka);
consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
return consumerProps;
}
where KafkaTestUtils.consumerProps()
does exactly what you ask:
return consumerProps(embeddedKafka.getBrokersAsString(), group, autoCommit);
...
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);
from spring-kafka.
@artembilan I believe the use case is for testing a production @Configuration
class that is not embedded within the test case - i.e. doesn't (and must not) have visibility to the embeddedKafka
static field.
from spring-kafka.
Oh! Sorry, my fault do not read the question.
Interesting, this works for me well:
@ClassRule
public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, ...);
@BeforeClass
public static void setup() {
System.setProperty("kafka.brokers", embeddedKafka.getBrokersAsString());
}
...
@Configuraiton
....
@Value("${kafka.brokers}")
private String brokers;
from spring-kafka.
Thank you Gary!! Pretty cool trick :)
from spring-kafka.
@artembilan 's solution is certainly simpler 😄
from spring-kafka.
Related Issues (20)
- Duplicate record consumption due to offset decrease in last offset commit HOT 2
- Infinite loop when retryable topic HOT 5
- Duplicate record consumption due to offset decrease in last offset commit HOT 1
- Duplicate record consumption due to offset decrease in last offset commit HOT 1
- Micrometer observation rewrites message header with invalid value HOT 2
- Enable KafkaStreamsMicrometerListener based on configuration HOT 5
- spring-kafka-3.1.1 version have no method ContainerProperties.setAuthorizationExceptionRetryInterval HOT 1
- KafkaTemplate currentSpan tagging issue
- KafkaTemplate currentSpan tagging issue HOT 1
- KafkaTemplate currentSpan tagging issue HOT 1
- Creation of `kafkaJaasInitializer` bean fails in a read-only filesystem due to creation of temporary file HOT 3
- Creation of `kafkaJaasInitializer` bean fails in a read-only filesystem due to creation of temporary file HOT 1
- Embedded Kafka throws NoSuchFileException HOT 7
- Implement CommonErrorHandler.handleOne() in CommonDelegatingErrorHandler HOT 1
- Implement CommonErrorHandler.handleOne() in CommonDelegatingErrorHandler HOT 1
- Implement CommonErrorHandler.handleOne() in CommonDelegatingErrorHandler HOT 1
- Switch `EmbeddedKafaka#kraft` default to `false`
- Pause a consumer for X minutes HOT 3
- Documentation for configuring custom `ConsumerFactory` and `ProducerFactory` beans when using Spring Boot is incorrect
- Documentation for configuring custom `ConsumerFactory` and `ProducerFactory` beans when using Spring Boot is incorrect HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from spring-kafka.