First off, this is very similar to this question.
What I'm trying to do is run a test that passes if the program doesn't throw a specific exception, but if the program does that specific exception, I want NUnit to put a message in the test runner explaining the likely cause of this specific exception.
Here's the situation, I'm doing the bowling score kata and I thought, what should happen if someone inputs a value for the 22nd roll (the highest number of rolls should every be 21 assuming a spare in the last frame).
My solution uses an array of 21 ints, and I've created a test that inputs 22 ints.
When I look at this page I see the option for this syntax:
Assert.DoesNotThrow( TestDelegate code, string message );
Here's what I think the line should look like, but I know (and the compiler is complaining) that using typeof is not going to get me the test delegate code.
[Test]
public void ShouldIgnore22ndRoll()
{
Assert.DoesNotThrow(typeof(System.IndexOutOfRangeException), "There should never be more than 21 rolls in a game");
RollAllTheSameNumber(1, 22);
}
Bottom line, I know what the problem is if I see this exception, and I want to tell my future me what that problem is (by populating the message that gets sent to the testrunner).
Any other exception, I'm going to have to figure out, but this exception is one I've already done the thinking for.
How would I write this assert?
Edit:
Here's the variable definitions:
int rollNumberDuringDataInput = 0;
const int AllowableNumberOfRolls = 21;
Here is the fixed code (silently ignoring any rolls past number 21):
public void AddPins(int pins)
{
if (rollNumberDuringDataInput < AllowableNumberOfRolls)
{
rolls[rollNumberDuringDataInput++] = pins;
}
}
Here is the code that will cause the test to fail by allowing more than 21 rolls:
public void AddPins(int pins)
{
rolls[rollNumberDuringDataInput++] = pins;
}
Currently, this is the message generated in the test runner: Message: System.IndexOutOfRangeException : Index was outside the bounds of the array.
What I want the message to be for this exception (and only this exception Message: System.IndexOutOfRangeException : There should never be more than 21 rolls in a game.
If someone removes the guard logic, I want the message in the test runner to tell me the business logic behind why that guard is there.
If you've never dealt with a whack-a-mole series of bugs (where one fix exposes an old vulnerability in the code, and that fix, exposes a different vulnerability, and that fix exposes the first error again; repeat) count yourself lucky.
I saw, what I thought, was a method to trap for a specific undesirable condition, that if it ever came back, we could quickly inform the breaking party, why their fix broke the code.