Sometimes it is necessary to assert when an exception is thrown. Different unit testing frameworks have different conventions for asserting that an exception was thrown, (like NUnit's Assert.Throws method). This example does not use any framework specific methods, just built in exception handling.
[Test]
public void GetItem_NegativeNumber_ThrowsArgumentInvalidException
{
ShoppingCart shoppingCartUnderTest = new ShoppingCart();
shoppingCartUnderTest.Add("apple");
shoppingCartUnderTest.Add("banana");
double invalidItemNumber = -7;
bool exceptionThrown = false;
try
{
shoppingCartUnderTest.GetItem(invalidItemNumber);
}
catch(ArgumentInvalidException e)
{
exceptionThrown = true;
}
Assert.True(exceptionThrown);
}