Like unit test for parellelism task

I have a class in .NET that creates and runs a new System.Threading.Tasks.Task as follows:

 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 methods of ScheduledTask.Start and ScheduledTask.Stop in C # .Net? What are the frameworks available for such unit tests and which are best practices for in-line testing of modules (or parallelism tasks)?

+4
source share
2 answers

Your class does a lot. Start / stop is a common function that should be in its 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 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); 

Then your other classes use StartStopTask to do their job.

Print

 public class ScheduledTask : StartStopTask { private IFoo _foo; public ScheduledTask(IFoo foo) : base(() => Run()) { _foo = foo; } private void Run(){ // Do some work } } 

Or just delegate 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 simply let Run be a public method and let the caller decide how to start it.

+5
source

You can try with the Mock task.

Best!

0
source

Source: https://habr.com/ru/post/1414354/


All Articles