I have an Azure Function which is an EventHub Trigger. The events are being processed in a batch EventData[]
.
[FunctionName("EventHubTriggerCSharp")]
public async Task Run([EventHubTrigger("samples-workitems", Connection = "EventHubConnectionAppSetting")] EventData[] eventHubMessages, ILogger log)
{
foreach (var message in eventHubMessages)
{
log.LogInformation($"C# function triggered to process a message: {Encoding.UTF8.GetString(message.Body)}");
log.LogInformation($"EnqueuedTimeUtc={message.SystemProperties.EnqueuedTimeUtc}");
await service.CallAsync(message);
}
}
How can one unit test a Function that requires a EventData[]
as the payload?
You should be able to construct the array of EventData
and pass that to the Run
method along with a mock logger instance.
I have used MsTest but it should be the same logic with NUnit.
[TestClass]
public class EventHubTriggerCSharpTests
{
private readonly Mock<IService> _mockService = new Mock<IService>();
private readonly Mock<ILogger> _mockLogger = new Mock<ILogger>();
private EventHubTriggerCSharp _eventHubTriggerCSharp;
[TestInitialize]
public void Initialize()
{
_eventHubTriggerCSharp = new EventHubTriggerCSharp(_mockService.Object);
}
[TestMethod]
public async Task WhenEventHubTriggersFunction_ThenCallAsyncWithEventHubMessage()
{
// arrange
var data = "some data";
var eventHubMessages = new List<EventData>
{
new EventData(Encoding.UTF8.GetBytes(data))
{
SystemProperties = new EventData.SystemPropertiesCollection(1, DateTime.Now, "offset", "partitionKey")
}
};
// act
await _eventHubTriggerCSharp.Run(eventHubMessages.ToArray(), _mockLogger.Object);
// assert
_mockService.Verify(x => x.CallAsync(eventHubMessages[0]));
}
}
Note: I haven't actually run the test due to an issue with my Visual Studio but hopefully you get the idea.