In the previous section, we learned how to write unit test cases for async code. In this section, we will discuss writing unit test cases for exception scenarios. Consider the following method:
private async Task<float> GetDivisionAsync(int number , int divisor)
{
if (divisor == 0)
{
throw new DivideByZeroException();
}
int result = await Task.Run(() =>
{
Thread.Sleep(1000);
return number / divisor;
});
return result;
}
The preceding method returns the result of the division of two numbers asynchronously. If the divisor is 0, then the DivideByZero exception is thrown by the method. We need two types of test cases to cover both scenarios:
- Checking for a successful result
- Checking for an exception result when the divisor is 0