c# - 单元测试无限轮询方法

标签 c# asynchronous xunit

我有一个方法,当应用程序启动时在新任务中启动,并在应用程序结束时停止。该方法每半秒执行一些逻辑。我对如何测试它感到非常困惑 - 有线索吗?

public async Task StartPoll(CancellationToken token)
{
  while(!token.IsCancellationRequested)
  {
    try 
    {
       var dict = dependecy.getDictionary();
       var model = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(dict));
       udpDistributer.Send(model, model.Length, _distributionEndPoint);
    }
    finally
    {
      await Task.Delay(500, Token);
    }
  }
}

其中 udpDistributer 是来自 DI 的 new UdpClient(0)_distributionEndPointIPEndPoint

基本上我想检查逻辑是否正常工作以及是否以正确的时间间隔发送正确的数据。我如何使用 xunit 来做到这一点?

编辑

我已经做到了这一点:

   // arrange
   ...
   cts = new CancellationTokenSource(timeout);

   //act
   await sut.StartPoll(cts.Token);

   // assert
   mockUdpDistributer.Verify(x => x.Send(expectedModel, expectedModel.length,
             It.IsAny<IPEndPoint>()), Times.Exactly(expectedTimes));

但是,这会导致测试失败并出现 TaskCanceledException

最佳答案

您验证udpDistributer.Send()(我假设您已注入(inject),如果没有,请执行此操作)在您需要的时间内被调用了适当的次数,然后取消 token 。

关于c# - 单元测试无限轮询方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66241895/

相关文章:

c# - 在 C# 中是否有与 Groovy 等效的东西?

c++ - FTP 异步操作上的 ERROR_IO_PENDING [Wininet C++]

xunit - 使用具有 NSubstitute 自动数据属性的 AutoFixture 时测试丢失

c# - 在 .Net Core 2.1 的 XUnit 单元测试中注册 AutoMapper

c# - 使用 T4 反射获取程序集

multithreading - Silverlight - 一次将应用程序限制为一个 WCF 调用

.net - Xunit 以下构造函数参数没有匹配的夹具数据

unit-testing - xUnit 异步测试无法正常工作

c# - 如何在保留调试器功能的同时从子进程报告自定义错误字符串

c++ - 使用 BOOST_ASIO_DISABLE_IOCP 有什么缺点?