Testing Spring Kafka Listener in Spring Boot Test with EmbeddedKafka

I’m trying to test a Spring Kafka listener in a Spring Boot test using @EmbeddedKafka. However, I keep encountering the following exception:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>No transaction is in process; possible solutions: run the template operation within the scope of a template.executeInTransaction() operation, start a transaction with @Transactional before invoking the template method, run in a transaction started by a listener container when consuming a record
java.lang.IllegalStateException: No transaction is in process; possible solutions: run the template operation within the scope of a template.executeInTransaction() operation, start a transaction with @Transactional before invoking the template method, run in a transaction started by a listener container when consuming a record
</code>
<code>No transaction is in process; possible solutions: run the template operation within the scope of a template.executeInTransaction() operation, start a transaction with @Transactional before invoking the template method, run in a transaction started by a listener container when consuming a record java.lang.IllegalStateException: No transaction is in process; possible solutions: run the template operation within the scope of a template.executeInTransaction() operation, start a transaction with @Transactional before invoking the template method, run in a transaction started by a listener container when consuming a record </code>
No transaction is in process; possible solutions: run the template operation within the scope of a template.executeInTransaction() operation, start a transaction with @Transactional before invoking the template method, run in a transaction started by a listener container when consuming a record

java.lang.IllegalStateException: No transaction is in process; possible solutions: run the template operation within the scope of a template.executeInTransaction() operation, start a transaction with @Transactional before invoking the template method, run in a transaction started by a listener container when consuming a record

My Setup:

  • Spring Boot Version: 3.2.4

Listener:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Component
@Slf4j
public class CancelAuthorizationLinkageListener {
private final CancelAuthorizationLinkageProcessor cancelAuthorizationLinkageProcessor;
private final CancelAuthorizationLinkageServiceInterface cancelAuthorizationLinkageService;
private final KafkaTemplate<String, CancelAuthorizationLinkageResource> kafkaTemplate;
private final String retryTopic;
public CancelAuthorizationLinkageListener(CancelAuthorizationLinkageProcessor cancelAuthorizationLinkageProcessor,
CancelAuthorizationLinkageServiceInterface cancelAuthorizationLinkageService,
KafkaTemplate<String, CancelAuthorizationLinkageResource> kafkaTemplate,
@Value("${spring.kafka.producer.retry-topic}") String retryTopic) {
this.cancelAuthorizationLinkageProcessor = cancelAuthorizationLinkageProcessor;
this.cancelAuthorizationLinkageService = cancelAuthorizationLinkageService;
this.kafkaTemplate = kafkaTemplate;
this.retryTopic = retryTopic;
}
@Bean
public RecordMessageConverter converter() {
return new JsonMessageConverter();
}
@Bean
public BatchMessagingMessageConverter batchConverter() {
return new BatchMessagingMessageConverter(converter());
}
@KafkaListener(id = "${spring.kafka.consumer.properties.cancel-authorization-linkage-listener-id}",
topics = "${spring.kafka.consumer.linkage-topic}", autoStartup = "false",
batch = "true",
groupId = "group1", concurrency = "2")
public void listen(List<CancelAuthorizationLinkageResource> cancelAuthorizationLinkageResources) {
for (CancelAuthorizationLinkageResource cancelAuthorizationLinkageResource : cancelAuthorizationLinkageResources) {
try {
CancelAuthorizationLinkageWriterResource cancelAuthorizationLinkageWriterResource =
cancelAuthorizationLinkageProcessor.process(cancelAuthorizationLinkageResource);
if (cancelAuthorizationLinkageWriterResource != null) {
cancelAuthorizationLinkageService.linkageAuthorization(
cancelAuthorizationLinkageWriterResource.getApiResource());
}
} catch (Exception e) {
log.error("listener error: {}", e.getMessage());
kafkaTemplate.send(retryTopic, cancelAuthorizationLinkageResource.getAuthorizationId(),
cancelAuthorizationLinkageResource);
}
}
}
</code>
<code>@Component @Slf4j public class CancelAuthorizationLinkageListener { private final CancelAuthorizationLinkageProcessor cancelAuthorizationLinkageProcessor; private final CancelAuthorizationLinkageServiceInterface cancelAuthorizationLinkageService; private final KafkaTemplate<String, CancelAuthorizationLinkageResource> kafkaTemplate; private final String retryTopic; public CancelAuthorizationLinkageListener(CancelAuthorizationLinkageProcessor cancelAuthorizationLinkageProcessor, CancelAuthorizationLinkageServiceInterface cancelAuthorizationLinkageService, KafkaTemplate<String, CancelAuthorizationLinkageResource> kafkaTemplate, @Value("${spring.kafka.producer.retry-topic}") String retryTopic) { this.cancelAuthorizationLinkageProcessor = cancelAuthorizationLinkageProcessor; this.cancelAuthorizationLinkageService = cancelAuthorizationLinkageService; this.kafkaTemplate = kafkaTemplate; this.retryTopic = retryTopic; } @Bean public RecordMessageConverter converter() { return new JsonMessageConverter(); } @Bean public BatchMessagingMessageConverter batchConverter() { return new BatchMessagingMessageConverter(converter()); } @KafkaListener(id = "${spring.kafka.consumer.properties.cancel-authorization-linkage-listener-id}", topics = "${spring.kafka.consumer.linkage-topic}", autoStartup = "false", batch = "true", groupId = "group1", concurrency = "2") public void listen(List<CancelAuthorizationLinkageResource> cancelAuthorizationLinkageResources) { for (CancelAuthorizationLinkageResource cancelAuthorizationLinkageResource : cancelAuthorizationLinkageResources) { try { CancelAuthorizationLinkageWriterResource cancelAuthorizationLinkageWriterResource = cancelAuthorizationLinkageProcessor.process(cancelAuthorizationLinkageResource); if (cancelAuthorizationLinkageWriterResource != null) { cancelAuthorizationLinkageService.linkageAuthorization( cancelAuthorizationLinkageWriterResource.getApiResource()); } } catch (Exception e) { log.error("listener error: {}", e.getMessage()); kafkaTemplate.send(retryTopic, cancelAuthorizationLinkageResource.getAuthorizationId(), cancelAuthorizationLinkageResource); } } } </code>
@Component
@Slf4j
public class CancelAuthorizationLinkageListener {
    private final CancelAuthorizationLinkageProcessor cancelAuthorizationLinkageProcessor;
    private final CancelAuthorizationLinkageServiceInterface cancelAuthorizationLinkageService;
    private final KafkaTemplate<String, CancelAuthorizationLinkageResource> kafkaTemplate;
    private final String retryTopic;

    public CancelAuthorizationLinkageListener(CancelAuthorizationLinkageProcessor cancelAuthorizationLinkageProcessor,
                                              CancelAuthorizationLinkageServiceInterface cancelAuthorizationLinkageService,
                                              KafkaTemplate<String, CancelAuthorizationLinkageResource> kafkaTemplate,
                                              @Value("${spring.kafka.producer.retry-topic}") String retryTopic) {
        this.cancelAuthorizationLinkageProcessor = cancelAuthorizationLinkageProcessor;
        this.cancelAuthorizationLinkageService = cancelAuthorizationLinkageService;
        this.kafkaTemplate = kafkaTemplate;
        this.retryTopic = retryTopic;
    }

    @Bean
    public RecordMessageConverter converter() {
        return new JsonMessageConverter();
    }

    @Bean
    public BatchMessagingMessageConverter batchConverter() {
        return new BatchMessagingMessageConverter(converter());
    }

    @KafkaListener(id = "${spring.kafka.consumer.properties.cancel-authorization-linkage-listener-id}",
            topics = "${spring.kafka.consumer.linkage-topic}", autoStartup = "false",
            batch = "true",
            groupId = "group1", concurrency = "2")
    public void listen(List<CancelAuthorizationLinkageResource> cancelAuthorizationLinkageResources) {
        for (CancelAuthorizationLinkageResource cancelAuthorizationLinkageResource : cancelAuthorizationLinkageResources) {
            try {
                CancelAuthorizationLinkageWriterResource cancelAuthorizationLinkageWriterResource =
                        cancelAuthorizationLinkageProcessor.process(cancelAuthorizationLinkageResource);
                if (cancelAuthorizationLinkageWriterResource != null) {
                    cancelAuthorizationLinkageService.linkageAuthorization(
                            cancelAuthorizationLinkageWriterResource.getApiResource());
                }
            } catch (Exception e) {
                log.error("listener error: {}", e.getMessage());
                kafkaTemplate.send(retryTopic, cancelAuthorizationLinkageResource.getAuthorizationId(),
                        cancelAuthorizationLinkageResource);
            }
        }
    }

Test:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
properties = {"spring.batch.job.name=cancelAuthorizationLinkageJob",
"bootstrap-servers: ${spring.embedded.kafka.brokers}"})
@DirtiesContext
@EmbeddedKafka(
partitions = 5, topics = {"${spring.kafka.consumer.linkage-topic}", "ppcd.cushion.cancel.auth.retry"},
count = 3)
class CancelAuthorizationLinkageListenerTest {
@Autowired
private CancelAuthorizationLinkageListener cancelAuthorizationLinkageListener;
@Mock
private CancelAuthorizationLinkageProcessor cancelAuthorizationLinkageProcessor;
@Autowired
private EmbeddedKafkaBroker embeddedKafka;
@Autowired
private ConsumerFactory<String, CancelAuthorizationLinkageResource> consumerFactory;
@Value("${spring.kafka.consumer.linkage-topic}")
private String linkageTopic;
@Value("${spring.kafka.producer.retry-topic}")
private String retryTopic;
private Consumer<String, CancelAuthorizationLinkageResource> consumer;
@BeforeEach
public void setUp() {
consumer = consumerFactory.createConsumer();
embeddedKafka.consumeFromAnEmbeddedTopic(consumer, retryTopic);
}
@Test
@DisplayName("OK-取消オーソリ処理中エラーが起きた場合、retryトピックへ送信する")
void of_ok_1() throws Exception {
// init
int ngNumber = 1;
AtomicInteger atomicInteger = new AtomicInteger(0);
// mock
doThrow(new InvalidValueException("test")).when(cancelAuthorizationLinkageProcessor).process(any());
// verify
cancelAuthorizationLinkageListener.listen(List.of(createCancelAuthorizationLinkageResource(true)));
await()
.atMost(2, SECONDS)
.pollInterval(1, SECONDS)
.untilAsserted(() -> {
KafkaTestUtils.getRecords(consumer).records(retryTopic)
.forEach(x -> atomicInteger.incrementAndGet());
assertEquals(ngNumber, atomicInteger.get());
});
}
</code>
<code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, properties = {"spring.batch.job.name=cancelAuthorizationLinkageJob", "bootstrap-servers: ${spring.embedded.kafka.brokers}"}) @DirtiesContext @EmbeddedKafka( partitions = 5, topics = {"${spring.kafka.consumer.linkage-topic}", "ppcd.cushion.cancel.auth.retry"}, count = 3) class CancelAuthorizationLinkageListenerTest { @Autowired private CancelAuthorizationLinkageListener cancelAuthorizationLinkageListener; @Mock private CancelAuthorizationLinkageProcessor cancelAuthorizationLinkageProcessor; @Autowired private EmbeddedKafkaBroker embeddedKafka; @Autowired private ConsumerFactory<String, CancelAuthorizationLinkageResource> consumerFactory; @Value("${spring.kafka.consumer.linkage-topic}") private String linkageTopic; @Value("${spring.kafka.producer.retry-topic}") private String retryTopic; private Consumer<String, CancelAuthorizationLinkageResource> consumer; @BeforeEach public void setUp() { consumer = consumerFactory.createConsumer(); embeddedKafka.consumeFromAnEmbeddedTopic(consumer, retryTopic); } @Test @DisplayName("OK-取消オーソリ処理中エラーが起きた場合、retryトピックへ送信する") void of_ok_1() throws Exception { // init int ngNumber = 1; AtomicInteger atomicInteger = new AtomicInteger(0); // mock doThrow(new InvalidValueException("test")).when(cancelAuthorizationLinkageProcessor).process(any()); // verify cancelAuthorizationLinkageListener.listen(List.of(createCancelAuthorizationLinkageResource(true))); await() .atMost(2, SECONDS) .pollInterval(1, SECONDS) .untilAsserted(() -> { KafkaTestUtils.getRecords(consumer).records(retryTopic) .forEach(x -> atomicInteger.incrementAndGet()); assertEquals(ngNumber, atomicInteger.get()); }); } </code>
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
        properties = {"spring.batch.job.name=cancelAuthorizationLinkageJob",
                "bootstrap-servers: ${spring.embedded.kafka.brokers}"})
@DirtiesContext
@EmbeddedKafka(
        partitions = 5, topics = {"${spring.kafka.consumer.linkage-topic}", "ppcd.cushion.cancel.auth.retry"},
        count = 3)
class CancelAuthorizationLinkageListenerTest {

    @Autowired
    private CancelAuthorizationLinkageListener cancelAuthorizationLinkageListener;

    @Mock
    private CancelAuthorizationLinkageProcessor cancelAuthorizationLinkageProcessor;

    @Autowired
    private EmbeddedKafkaBroker embeddedKafka;

    @Autowired
    private ConsumerFactory<String, CancelAuthorizationLinkageResource> consumerFactory;

    @Value("${spring.kafka.consumer.linkage-topic}")
    private String linkageTopic;

    @Value("${spring.kafka.producer.retry-topic}")
    private String retryTopic;

    private Consumer<String, CancelAuthorizationLinkageResource> consumer;

    @BeforeEach
    public void setUp() {
        consumer = consumerFactory.createConsumer();
        embeddedKafka.consumeFromAnEmbeddedTopic(consumer, retryTopic);
    }

    @Test
    @DisplayName("OK-取消オーソリ処理中エラーが起きた場合、retryトピックへ送信する")
    void of_ok_1() throws Exception {
        // init
        int ngNumber = 1;
        AtomicInteger atomicInteger = new AtomicInteger(0);

        // mock
        doThrow(new InvalidValueException("test")).when(cancelAuthorizationLinkageProcessor).process(any());

        // verify
        cancelAuthorizationLinkageListener.listen(List.of(createCancelAuthorizationLinkageResource(true)));

        await()
                .atMost(2, SECONDS)
                .pollInterval(1, SECONDS)
                .untilAsserted(() -> {
                    KafkaTestUtils.getRecords(consumer).records(retryTopic)
                            .forEach(x -> atomicInteger.incrementAndGet());
                    assertEquals(ngNumber, atomicInteger.get());
                });
    }

application.yml:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>spring:
profiles:
active: "local"
application:
name:
batch:
initialize-schema: ALWAYS
job:
names:
#enable: false
kafka:
bootstrap-servers: localhost:9092
producer:
acks: -1
transaction-id-prefix: cushion-kafka-tx-${random.uuid}
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
retry-topic: ppcd.cushion.cancel.auth.retry
# retries: 5
consumer:
group-id: groupid-Dev
auto-offset-reset: earliest
max-poll-records: 20
value-deserializer: org.apache.kafka.common.serialization.ByteArrayDeserializer
properties:
cancel-authorization-linkage-listener-id: cancel-authorization-linkage-listener
test-cancel-authorization-linkage-listener-id: test-cancel-authorization-linkage-listener
spring.json.trusted.packages: '*'
isolation.level: read_committed
linkage-topic: ppcd.matching.credit.auth.cancel.auto.matched.result.cushion
</code>
<code>spring: profiles: active: "local" application: name: batch: initialize-schema: ALWAYS job: names: #enable: false kafka: bootstrap-servers: localhost:9092 producer: acks: -1 transaction-id-prefix: cushion-kafka-tx-${random.uuid} value-serializer: org.springframework.kafka.support.serializer.JsonSerializer retry-topic: ppcd.cushion.cancel.auth.retry # retries: 5 consumer: group-id: groupid-Dev auto-offset-reset: earliest max-poll-records: 20 value-deserializer: org.apache.kafka.common.serialization.ByteArrayDeserializer properties: cancel-authorization-linkage-listener-id: cancel-authorization-linkage-listener test-cancel-authorization-linkage-listener-id: test-cancel-authorization-linkage-listener spring.json.trusted.packages: '*' isolation.level: read_committed linkage-topic: ppcd.matching.credit.auth.cancel.auto.matched.result.cushion </code>
spring:
  profiles:
    active: "local"
  application:
    name:
  batch:
    initialize-schema: ALWAYS
    job:
      names:
      #enable: false
  kafka:
    bootstrap-servers: localhost:9092
    producer:
      acks: -1
      transaction-id-prefix: cushion-kafka-tx-${random.uuid}
      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
      retry-topic: ppcd.cushion.cancel.auth.retry

    #      retries: 5
    consumer:
      group-id: groupid-Dev
      auto-offset-reset: earliest
      max-poll-records: 20
      value-deserializer: org.apache.kafka.common.serialization.ByteArrayDeserializer
      properties:
        cancel-authorization-linkage-listener-id: cancel-authorization-linkage-listener
        test-cancel-authorization-linkage-listener-id: test-cancel-authorization-linkage-listener
        spring.json.trusted.packages: '*'
        isolation.level: read_committed
      linkage-topic: ppcd.matching.credit.auth.cancel.auto.matched.result.cushion

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật