Skip to content

Commit

Permalink
fix: preserve message context items when SetMessage is called
Browse files Browse the repository at this point in the history
  • Loading branch information
esskar authored and JoaoRodriguesGithub committed Mar 1, 2024
1 parent dc0882f commit 4f79c43
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/KafkaFlow/MessageContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,25 @@ public MessageContext(
IConsumerContext consumer,
IProducerContext producer,
IReadOnlyCollection<string> brokers)
: this(message, headers, dependencyResolver, consumer, producer, brokers, new Dictionary<string, object>())
{
}

private MessageContext(
Message message,
IMessageHeaders headers,
IDependencyResolver dependencyResolver,
IConsumerContext consumer,
IProducerContext producer,
IReadOnlyCollection<string> brokers,
IDictionary<string, object> items)
{
this.Message = message;
this.DependencyResolver = dependencyResolver;
this.Headers = headers ?? new MessageHeaders();
this.ConsumerContext = consumer;
this.ProducerContext = producer;
this.Items = new Dictionary<string, object>();
this.Items = items;
this.Brokers = brokers;
}

Expand All @@ -41,5 +53,6 @@ public MessageContext(
this.DependencyResolver,
this.ConsumerContext,
this.ProducerContext,
this.Brokers);
this.Brokers,
this.Items);
}
39 changes: 39 additions & 0 deletions tests/KafkaFlow.UnitTests/MessageContextTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System.Collections.Generic;
using KafkaFlow.Consumers;
using KafkaFlow.Producers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace KafkaFlow.UnitTests;

[TestClass]
public class MessageContextTests
{
[TestMethod]
public void SetMessage_ShouldSetMessageCorrectly()
{
// Arrange
var messageContext = new MessageContext(
new Message("key", "value"),
Mock.Of<IMessageHeaders>(),
Mock.Of<IDependencyResolver>(),
Mock.Of<IConsumerContext>(),
Mock.Of<IProducerContext>(),
Mock.Of<IReadOnlyCollection<string>>()
);


// Act
var changedMessage = messageContext.SetMessage("changed-key", "changed-value");

// Assert
Assert.AreEqual("changed-key", changedMessage.Message.Key);
Assert.AreEqual("changed-value", changedMessage.Message.Value);
Assert.AreSame(messageContext.ConsumerContext, changedMessage.ConsumerContext);
Assert.AreSame(messageContext.DependencyResolver, changedMessage.DependencyResolver);
Assert.AreSame(messageContext.Headers, changedMessage.Headers);
Assert.AreSame(messageContext.ProducerContext, changedMessage.ProducerContext);
Assert.AreSame(messageContext.Brokers, changedMessage.Brokers);
Assert.AreSame(messageContext.Items, changedMessage.Items);
}
}

0 comments on commit 4f79c43

Please sign in to comment.