Home > database >  Unit testing a method whose statements run on different task
Unit testing a method whose statements run on different task

Time:02-22

I have a method:

public class WorkerClass : IWorkerClass
{
private int myworkId = 0;
public void Workflow(int theWorkid)
        {
            var aTask = new Task(() =>
            {
                this.myworkId = theWorkid;
                //Some calculations
              
            });

            aTask.Start();
        }
}

I have a Unit test method :

[DataTestMethod]
[DataRow(23)]
public class workerTester
{
 public void WorkflowTest(int theWorkflowMode)
        {
            // Arrange 
           
            var aWorkTester = new Mock<IWorkerClass>();
            var aExpectedWorkflowMode = 23;
            myWorkerPrivateObj = new PrivateObject(aWorkTester);

            // Act

            myWorkerPrivateObj .Invoke("Workflow", theWorkflowMode);

            // Assert

            //Thread.Sleep(1000); If i uncomment it works
            var aActualWorkflowModeType = myWorkerPrivateObj.GetField("myworkId");
            Assert.AreEqual(aExpectedWorkflowModeType, aActualWorkflowModeType);
            
        }
}

If i uncomment Thread.Sleep(1000), aActualWorkflowModeType comes as 23. But if i comment it aActualWorkflowModeType comes as 0. I am assuming my assert is called before my task is complete. How can i wait until task is complete in my Unit test?

CodePudding user response:

I figured out a way to do it for unit testing:

     var lookupTask = Task<WorkerClass>.Factory.StartNew(() =>
                {
                    return new WorkerClass();
                });
    
                lookupTask.Wait();

So my new Unit test method looks like this :

[DataTestMethod]
[DataRow(23)]
public class workerTester
{
 public void WorkflowTest(int theWorkflowMode)
        {
            // Arrange 
           
            var aWorkTester = new Mock<IWorkerClass>();
            var aExpectedWorkflowMode = 23;
            myWorkerPrivateObj = new PrivateObject(aWorkTester);

            // Act

            myWorkerPrivateObj .Invoke("Workflow", theWorkflowMode);
            var lookupTask = Task<WorkerClass>.Factory.StartNew(() =>
                {
                    return new WorkerClass();
                });

            // Assert
            lookupTask.Wait();
            var aActualWorkflowModeType = myWorkerPrivateObj.GetField("myworkId");
            Assert.AreEqual(aExpectedWorkflowModeType, aActualWorkflowModeType);
            
        }
}

This seems to work

  • Related