我正在使用InMemoryTestHarness进行单元测试使用者,该使用者处理带有MessageData属性的命令。使用InMemoryMessageDataRepository填充MessageData属性可以正常工作,但是,当使用者尝试加载有效负载(message.Body.Value)时,我收到以下异常:“未加载消息数据:urn:msgdata:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx”}。对使用MessageData属性处理命令的使用者进行单元测试的正确方法是什么?
我本来要使用内存中的传输方式,但是由于单元测试不会立即从消费者那里得到反馈,因此这似乎不是正确的方法。最终,最终目的是使我的单元测试能够断言抛出了特定的异常或使用者成功完成了操作而没有错误。
using System;
using System.Linq;
using System.Threading.Tasks;
using MassTransit;
using MassTransit.MessageData;
using MassTransit.Testing;
using Newtonsoft.Json;
using Xunit;
namespace Test
{
public class LargePayloadConsumerTest
{
[Fact]
public async Task Consumer_Should_Deserialize_Message()
{
var harness = new InMemoryTestHarness();
var consumer = harness.Consumer<BigMessageConsumer>();
var command = new BigMessageCommand();
var dataRepo = new InMemoryMessageDataRepository();
var largePayload = new BigMessagePayload()
{
Id = 1,
FirstName = "TestFirstName",
MiddleName = "TestMiddleName",
LastName = "TestLastName"
};
var json = JsonConvert.SerializeObject(largePayload);
command.Body = await dataRepo.PutString(json);
var thisWorks = await command.Body.Value;
await harness.Start();
await harness.InputQueueSendEndpoint.Send(command);
Assert.True(harness.Consumed.Select<BigMessageCommand>().Any());
}
public class BigMessageConsumer : IConsumer<BigMessageCommand>
{
public async Task Consume(ConsumeContext<BigMessageCommand> context)
{
try
{
var json = await context.Message.Body.Value;
var deserialized = JsonConvert.DeserializeObject<BigMessagePayload>(json);
Console.WriteLine($"{deserialized.Id}: {deserialized.FirstName} {deserialized.MiddleName} {deserialized.LastName}");
}
catch (Exception e)
{
//throws {"The message data was not loaded: urn:msgdata:xxxxxxxxxxxxxxxxxxxxxxxxxx"}
Console.WriteLine(e);
throw;
}
}
}
public class BigMessageCommand
{
public MessageData<string> Body { get; set; }
}
public class BigMessagePayload
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
}
}
}
答案 0 :(得分:0)
您需要配置接收端点以处理消息数据属性,类似于以下内容:
e.UseMessageData<BigMessageCommand>(dataRepo);
由于您正在使用测试工具,因此可以在添加消费者测试工具之前将其添加到接收端点 :
void ConfigureReceiveEndpoint(IReceiveEndpointConfigurator configurator)
{
configurator.UseMessageData<BigMessageCommand>(dataRepo);
}
harness.OnConfigureReceiveEndpoint += ConfigureReceiveEndpoint;