【发布时间】:2022-01-13 15:49:56
【问题描述】:
我有委托调用 SendMessagesAsync 方法,该方法采用 IEnumerable ProviderExemptionReceivedNotification。我如何模拟作为委托回调的 SendMessagesAsync。换句话说,我如何起订委托?
Interface
public delegate Task<bool> SendAnprProviderExemptionNotifications(IEnumerable<ProviderExemptionReceivedNotification> exemptions);
public interface IRingGoApiService
{
Task<RingGoMessageResponseResult> ProcessCreateRequestAsync(RingGoExemption ringGoExemption, SendAnprProviderExemptionNotifications sendProviderExemption);
}
Delegate Implementation
public async Task<RingGoMessageResponseResult> ProcessCreateRequestAsync(RingGoExemption ringGoExemption, SendAnprProviderExemptionNotifications sendProviderExemption)
{
var msgSent = await sendProviderExemption(new List<ProviderExemptionReceivedNotification>() { exemption });
}
Test Class
public MyTestClass{
public MyTestClass()
{
}
private readonly Mock<IProviderExemptionService> providerExemptionServiceMoq;
}
using delegate
var result = await _ringGoApiService.ProcessCreateRequestAsync(ringGoExemption,
async (IEnumerable<ProviderExemptionReceivedNotification> exemptions) => await SendMessagesAsync(servicebusMessage, exemptions)
);
SendMessagesAsync
static async Task<bool> SendMessagesAsync(IAsyncCollector<Message> collector, IEnumerable<ProviderExemptionReceivedNotification> exemptions)
{
SetProviderExemption(exemptions);
var messages = exemptions.Select(exemption =>
{
//Creating ServiceBus Message...
return message;
});
}
static void SetProviderExemption(IEnumerable<ProviderExemptionReceivedNotification> exemptions)
{
providerExemption = exemptions.FirstOrDefault();
}
【问题讨论】:
-
你不能模拟委托。但是您可以在测试代码中创建一个委托,只要它与
SendAnprProviderExemptionNotifications具有相同的签名,它就可以执行您想要的任何操作,并将其作为参数传递给您正在测试的方法。 -
参考我的问题中的部分
using delegate有 lambda 表达式 SendMessageAsync .. 那么我如何模拟呢? -
您也不能模拟该表达式,因为它被硬编码到表达式中。您需要在回调中捕获委托并在那里调用它。鉴于显示的测试对象,这是唯一可用的选项。
-
你能在语法上帮我吗.. 我在设置中的 SendMessagesAsync(servicebusMessage, excludes) 回调上苦苦挣扎
-
ringGoApiServiceMoq.Setup(x => x.ProcessCreateRequestAsync(It.IsAny
(), It.IsAny ())) .ReturnsAsync(ringGoMessageResponseResultMoq) .Callback(providerExemptionReceivedNotificationMoq));
标签: c# .net-core delegates xunit