Testing Basics
Expected Exception
Model a test that expects an exception for one input shape.
Expected Exception
ExpectedException.cs
using System;
class Program
{
static int Divide(int numerator, int denominator)
{
return numerator / denominator;
}
static void Main()
{
int denominator = ;
bool expectedException = denominator == 0;
bool sawException = false;
string outcome = "completed";
try
{
int value = Divide(10, denominator);
outcome = $"value={value}";
}
catch (DivideByZeroException)
{
sawException = true;
outcome = "divide-by-zero";
}
bool testPassed = sawException == expectedException;
Console.WriteLine($"expectedException={expectedException}");
Console.WriteLine($"sawException={sawException}");
Console.WriteLine($"outcome={outcome}");
Console.WriteLine($"testPassed={testPassed}");
}
}
using System;
class Program
{
static int Divide(int numerator, int denominator)
{
return numerator / denominator;
}
static void Main()
{
int denominator = ;
bool expectedException = denominator == 0;
bool sawException = false;
string outcome = "completed";
try
{
int value = Divide(10, denominator);
outcome = $"value={value}";
}
catch (DivideByZeroException)
{
sawException = true;
outcome = "divide-by-zero";
}
bool testPassed = sawException == expectedException;
Console.WriteLine($"expectedException={expectedException}");
Console.WriteLine($"sawException={sawException}");
Console.WriteLine($"outcome={outcome}");
Console.WriteLine($"testPassed={testPassed}");
}
}
using System;
class Program
{
static int Divide(int numerator, int denominator)
{
return numerator / denominator;
}
static void Main()
{
int denominator = ;
bool expectedException = denominator == 0;
bool sawException = false;
string outcome = "completed";
try
{
int value = Divide(10, denominator);
outcome = $"value={value}";
}
catch (DivideByZeroException)
{
sawException = true;
outcome = "divide-by-zero";
}
bool testPassed = sawException == expectedException;
Console.WriteLine($"expectedException={expectedException}");
Console.WriteLine($"sawException={sawException}");
Console.WriteLine($"outcome={outcome}");
Console.WriteLine($"testPassed={testPassed}");
}
}
testing
Exception tests pass when the expected exception is observed and fail when the code completes unexpectedly.