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);
});
}
It's a tremendously bad idea to have a try/catch which, in the catch block, squashes the exception.
Yes, it's possible for the
calculate.calculatorResult /= item;line to throw aDivideByZeroException, but because of the way you've written the catch block, it's impossible for your method to throw aDivideByZeroException.If you still want the exception to be written to the console, then rethrow the exception.