Unit test cases failing for async method

Sunil A M 171 Reputation points
2023-03-17T07:02:50.9733333+00:00

Hi Team,

I have one method like below.

private async string ProcessMonitor_OnProcessStopped(object sender, ProcessDetails processDetails)

{

await Task.Delay(500);

return "Value";

}

and i am writing the unit test case for the above method.

Since its waiting in task.delay(500), my test cases are failing because it failing to return the value from the method on time,

Help me on this.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,097 questions
Visual Studio Testing
Visual Studio Testing
Visual Studio: A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.Testing: The act or process of applying tests as a means of analysis or diagnosis.
323 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Tasadduq Burney 8,356 Reputation points MVP
    2023-03-17T07:28:36.7933333+00:00

    You can try modifying your code to allow for asynchronous testing.

    One approach you could take is to use TaskCompletionSource to signal the completion of the task in your test case. Here's an example of how you could modify your code to implement this approach:

    private async Task<string> ProcessMonitor_OnProcessStopped(object sender, ProcessDetails processDetails)
    {
        await Task.Delay(500);
        return "Value";
    }
    [TestMethod]
    public async Task TestProcessMonitor_OnProcessStopped()
    {
        var tcs = new TaskCompletionSource<string>();
        var processDetails = new ProcessDetails(); // Create process details as needed
        
        var resultTask = ProcessMonitor_OnProcessStopped(null, processDetails);
        resultTask.ContinueWith(t => tcs.SetResult(t.Result));
        
        // Wait for the result or a timeout
        var completedTask = await Task.WhenAny(tcs.Task, Task.Delay(1000));
        
        Assert.AreEqual("Value", completedTask.Result);
    }
    

    This modified test case creates a TaskCompletionSource<string> to signal the completion of the task