1 package de.juplo.kafka.wordcount.recorder;
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRecord;
5 import org.junit.jupiter.api.DisplayName;
6 import org.junit.jupiter.api.Test;
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
9 import org.springframework.boot.test.context.SpringBootTest;
10 import org.springframework.boot.test.context.TestConfiguration;
11 import org.springframework.context.annotation.Bean;
12 import org.springframework.http.MediaType;
13 import org.springframework.kafka.annotation.KafkaListener;
14 import org.springframework.kafka.test.context.EmbeddedKafka;
15 import org.springframework.test.web.servlet.MockMvc;
16 import org.springframework.test.web.servlet.MvcResult;
17 import org.springframework.util.LinkedMultiValueMap;
18 import org.springframework.util.MultiValueMap;
20 import static de.juplo.kafka.wordcount.recorder.ApplicationTests.PARTITIONS;
21 import static de.juplo.kafka.wordcount.recorder.ApplicationTests.TOPIC_OUT;
22 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
23 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
24 import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
25 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
26 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
31 "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}",
32 "juplo.wordcount.recorder.bootstrap-server=${spring.embedded.kafka.brokers}",
33 "juplo.wordcount.recorder.topic=" + TOPIC_OUT })
35 @EmbeddedKafka(topics = { TOPIC_OUT }, partitions = PARTITIONS)
37 class ApplicationTests
39 static final String TOPIC_OUT = "out";
40 static final int PARTITIONS = 2;
41 static final String USER = "päter";
42 static final String SENTENCE = "Hall° Wält?¢*&%€!";
46 private MockMvc mockMvc;
49 @DisplayName("The application context loads")
55 void userMessagesAreExceptedAndSentToKafka() throws Exception
57 MvcResult result = mockMvc
58 .perform(post("/{user}", USER)
59 .contentType(MediaType.TEXT_PLAIN)
63 mockMvc.perform(asyncDispatch(result))
65 .andExpect(status().isOk())
66 .andExpect(jsonPath("$.username").value(USER))
67 .andExpect(jsonPath("$.sentence").value(SENTENCE));
72 final MultiValueMap<String, String> received = new LinkedMultiValueMap<>();
74 @KafkaListener(groupId = "TEST", topics = TOPIC_OUT)
75 public void receive(ConsumerRecord<String, String> record)
77 log.debug("Received message: {}", record);
78 received.add(record.key(), record.value());
83 static class Configuration
88 return new Consumer();