2

I'm trying to use Embedded kafka for my tests.I'm using spring boot and junit5 as follows

@SpringBootTest
@EmbeddedKafka
public class MyTest {
//Instead of the class rule approach I'm using
EmbeddedKafkaBroker embeddedKafka = new EmbeddedKafkaBroker(1,true,topics);
..
@Test
public void myTestCase() {
....

}

However,my tests fail with the No resolvable bootstrap urls given in bootstrap servers

I'm using a test profile too where on the yml file I've

 bootstrap-servers :{spring.embedded.kafka.brokers}

Please help.

Vendetta
  • 2,078
  • 3
  • 13
  • 31
Chetya
  • 1,267
  • 1
  • 17
  • 31

1 Answers1

1

@SpringBootTest initializes the test Spring Boot application context before the test class instance is created and member fields are initialized. Because of that the @SpringBootApplication doesn't see the EmbeddedKafkaBroker as the field is initialized later.

Try following a working example from this answer:

@SpringBootTest
@EnableKafka
@EmbeddedKafka(
    partitions = 1, 
    controlledShutdown = false,
    brokerProperties = {
        "listeners=PLAINTEXT://localhost:3333", 
        "port=3333"
})
public class KafkaConsumerTest {
    @Autowired
    KafkaEmbedded kafkaEmbeded;
}

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • 2
    Right - the OP has two brokers, the one added to the Spring context via the annotation and the field initialized manually; autowiring the `EmbeddedKafkaBroker` is the correct approach (`KafkaEmbedded` is deprecated in 2.2.x and doesn't exist in current versions). Just for completion, `@EmbeddedKafka` works with a vanilla (non-spring) test as well, via the `EmbeddedKafkaCondition`, and the broker instance is available via `EmbeddedKafkaCondition.getBroker()` to get access to the broker URL(s). – Gary Russell Jan 30 '20 at 16:23
  • 2
    With Spring Boot tests, you can also use `@EmbeddedKafka(..., bootstrapServersProperty = "spring.kafka.bootstrap-servers")` to override the boot property in application.yml. – Gary Russell Jan 30 '20 at 16:26