【问题标题】:C# NUnit Testing for Timer定时器的 C# NUnit 测试
【发布时间】:2023-03-05 09:49:01
【问题描述】:

我是单元测试的新手,刚刚开始学习它。这是我要测试的代码。这是 System.Threading.Timer 的包装器,保证不会泄漏异常。提前感谢您的帮助。

<pre>
using System;
using System.Threading;

namespace MCC.Test.Unit
{

    public class MyTimer : IDisposable
    {
        private static readonly TimeSpan NoAutoStartTimer = TimeSpan.FromMilliseconds(-1);
        private readonly Object _synclock = new object();
        private Timer _internalTimer;

        public MyTimer()
        {
            _internalTimer = new Timer(TimerTick);
        }


        public MyTimer(Action tickHandler) : this()
        {
            Tick += tickHandler;
        }

        public void Dispose()
        {
            if (_internalTimer != null)
            {
                try
                {
                    lock (_synclock)
                    {
                        _internalTimer.Dispose();
                        _internalTimer = null;
                        foreach (Delegate d in Tick.GetInvocationList())
                        {
                            Tick -= (Action) d;
                        }
                    }
                }
                catch (Exception err)
                {
                    Console.Error.WriteLine(err);
                }
            }
        }

        /// <summary>
        ///     Called when the timer ticks
        /// </summary>
        public event Action Tick;

        private void TimerTick(Object state)
        {
            try
            {
                if (Tick != null)
                {
                    Tick();
                }
            }
            catch (Exception err)
            {
                Console.Error.WriteLine(err);
            }
        }

        /// <summary>
        ///     Schedules the next tick
        /// </summary>
        /// <param name="next">The duration until the next sprint</param>
        public void TriggerNextTickIn(TimeSpan next)
        {
            try
            {
                lock (_synclock)
                {
                    if (_internalTimer != null)
                    {
                        _internalTimer.Change(next, NoAutoStartTimer);
                    }
                }
            }
            catch (Exception err)
            {
                Console.Error.WriteLine(err);
            }
        }
    }
}
</pre>

【问题讨论】:

  • 您的问题是什么?如果您只是在寻找代码审查,也可以查看 codereview.stackexchange.com
  • 问题是如何检查计时器是否计时,谢谢

标签: c# unit-testing testing nunit


【解决方案1】:

这里有很多要测试的:

  • 测试创建/初始化
  • 检查Tick是否来了
  • 当没有人注册到Tick时,检查您的代码是否失败
  • 测试TriggerNextTickIn

将您的代码视为一个块框以及它所承诺的内容,并检查它是否符合该承诺。最好在完成代码之前编写测试......

【讨论】:

    猜你喜欢
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多