Xunit Testing on a DivideByZeroException

161 Views Asked by At

I am a beginner at C# and Xunit testing. I have this body of code that denotes a Division method.

 public void Divide(CalculatorData calculate)
    {
        calculate.Operator = CalculatorOperator.Divide;
        calculate.calculatorResult = calculate.inputNumbers[0];
        for (int i = 1; i < calculate.inputNumbers.Length; i++)
        {
            decimal item = calculate.inputNumbers[i];
            try
            {
                calculate.calculatorResult /= item;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }

I tried this unit testing, but it doesn't pass. Anyone knows how should I approach this?

 public void Divide_DivByZero()
    {
        //Arrange
        calculatorData.inputNumbers = new List<decimal>() { 5, 0 }.ToArray();

        Assert.Throws<DivideByZeroException>(() =>
        {

            //Act
            calculatorManager.Divide(calculatorData);
            var result = calculatorData.calculatorResult;

            //Assert
            Assert.IsType<decimal>(result);
        });
    }
1

There are 1 best solutions below

0
gunr2171 On

It's a tremendously bad idea to have a try/catch which, in the catch block, squashes the exception.

try
{
    calculate.calculatorResult /= item;
}
catch (DivideByZeroException e)
{
    Console.WriteLine(e.Message);
}

Yes, it's possible for the calculate.calculatorResult /= item; line to throw a DivideByZeroException, but because of the way you've written the catch block, it's impossible for your method to throw a DivideByZeroException.

If you still want the exception to be written to the console, then rethrow the exception.

try
{
    calculate.calculatorResult /= item;
}
catch (DivideByZeroException e)
{
    Console.WriteLine(e.Message);
    throw;
}