我无法模拟 ServiceBusReceivedMessage 和 ServiceBusMessageActions
我们想为服务总线消息触发器编写单元测试。我们正在使用 Azure.Messaging.ServiceBus nuget 包
[FunctionName("serviebustrigger")]
public async Task Run ([ServiceBusTrigger("xxxxtopic", "xxxxsubscription", Connection = "Abs-Connection", AutoCompleteMessages = false)] ServiceBusReceivedMessage message, ServiceBusMessageActions messageActions)
{
_logger.LogInformation($"{nameof(Run)} execution started for MessageId:{{MessageId}}", message.MessageId);
try
{
//some code
await messageActions.CompleteMessageAsync(message);
}
catch (Exception ex)
{
await messageActions.DeadLetterMessageAsync(message);
}
}
现在我想写单元测试上面的代码。但我无法模拟 ServiceBusReceivedMessage 和 ServiceBusMessageActions 因为它们有内部构造函数。有人可以建议我更好的方法来编写单元测试
we want to write unit-test for servicebus message trigger. we are using Azure.Messaging.ServiceBus nuget package
[FunctionName("serviebustrigger")]
public async Task Run ([ServiceBusTrigger("xxxxtopic", "xxxxsubscription", Connection = "Abs-Connection", AutoCompleteMessages = false)] ServiceBusReceivedMessage message, ServiceBusMessageActions messageActions)
{
_logger.LogInformation(quot;{nameof(Run)} execution started for MessageId:{{MessageId}}", message.MessageId);
try
{
//some code
await messageActions.CompleteMessageAsync(message);
}
catch (Exception ex)
{
await messageActions.DeadLetterMessageAsync(message);
}
}
Now I want to write unit test for the above code. But I'm not able mock ServiceBusReceivedMessage and ServiceBusMessageActions as these have Internal Constructor. Can someone suggest me better way to write unit test
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ServiceBusMessageActions
的实现存在一个疏忽,最初错过了模拟构造函数。此问题已在 v5.2.0 中得到纠正扩展包。通过此修复,无参数构造函数可确保 ServiceBusMessageActions 可与 Moq 或 FakeItEasy 等模拟框架一起使用。每个公共成员都是
虚拟
或可设置的,并且该类不是密封的。您应该能够使用与其他类型相同的方法进行模拟 - 无论是使用模拟框架还是从类继承并创建您自己的模拟类型 - 并利用模型工厂来模拟行为。对于 ServiceBusReceivedMessage 和服务操作返回的其他模型类型,ServiceBusModelFactory 用于创建用于测试目的的实例。
There was an oversight with the implementation of
ServiceBusMessageActions
where the mocking constructor was initially missed. This was corrected in v5.2.0 of the extensions package.With that fix, a parameterless constructor is available to ensure that
ServiceBusMessageActions
is usable with a mocking framework such as Moq or FakeItEasy. Each of the public members arevirtual
or settable and the class is not sealed. You should be able to mock using the same approach that you prefer for other types - whether with a mocking framework or inheriting from the class and creating your own mock type - and make use of the model factory to simulate behavior.For
ServiceBusReceivedMessage
and other model types that are returned by service operations, the ServiceBusModelFactory is used to create instances for testing purposes.