简体   繁体   English

如何对任务parellelism进行单元测试

[英]How to unit test for Task parellelism

I have a class in .NET which creates and starts a new System.Threading.Tasks.Task as follows: 我在.NET中有一个类,它创建并启动一个新的System.Threading.Tasks.Task ,如下所示:

public class ScheduledTask
{
    private IFoo _foo;

    public ScheduledTask(IFoo foo)
    {
        _foo = foo;
    }

    public void Start()
    {           
        _task = new Task(() => Run());
        _task.Start();
    }

    public void Stop(TimeSpan timeout)
    {
        var taskCompletedNormally = _task.Wait(timeout);
        if (taskCompletedNormally)
        {                
            _task.Dispose();
            _task = null;                
        }
    }

    private void Run(){ // Do some work}
}

How do I unit test the ScheduledTask.Start and ScheduledTask.Stop methods in C#.Net? 如何在C#.Net中对ScheduledTask.StartScheduledTask.Stop方法进行单元测试? Which are the frameworks available for such unit tests and which are the best practices for unit testing threading (or task parallelism)? 哪些是可用于此类单元测试的框架,哪些是单元测试线程(或任务并行)的最佳实践?

Your class is doing to much. 你的班级做得很多。 Start/stop is a generic function that should be in its own class. 启动/停止是一个通用函数,应该在它自己的类中。

public class StartStopTask
{
    private readonly Action _action;

    public StartStopTask(Action action)
    {
        _action = action;
    }

    public void Start()
    {           
        _task = new Task(_action);
        _task.Start();
    }
    ...
}

This class is easy to unit test. 这个类很容易进行单元测试。

bool worked = false;
var startstop = new StartStopTask(() => { worked = true });
startstop.Start();
startstop.Stop(new TimeSpan(0,0,0,10));
Assert.That(worked, Is.True);

Your other classes then uses the StartStopTask to do its work. 然后,您的其他类使用StartStopTask来完成其工作。

Either derive 要么得出

public class ScheduledTask : StartStopTask
{
    private IFoo _foo;

    public ScheduledTask(IFoo foo)
        : base(() => Run())
    {
        _foo = foo;
    }

    private void Run(){ // Do some work }
}

Or just delegate the work 或者只是委托工作

public class ScheduledTask
{
    private IFoo _foo;
    private readonly StartStopTask _startstop;

    public ScheduledTask(IFoo foo)
    {
        _foo = foo;
        _startstop = new StartStopTask(() => Run());
    }

    public void Start()
    {           
        _startstop.Start();
    }

    public void Stop(TimeSpan timeout)
    {
        _startstop.Stop(timeout);
    }

    private void Run(){ // Do some work }
}

Even better would be to just let Run be a public method and let the caller decide how it should be run. 更好的方法是让Run成为一个公共方法,让调用者决定它应该如何运行。

You can try with Mock task. 你可以试试Mock任务。

Best ! 最好 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM