My solution involves a couple of items to implement, but at the very end it will look much more elegant:
@CatchException
Scenario: Faulty operation throws exception
Given Some Context
When Some faulty operation invoked
Then Exception thrown with type 'ValidationException' and message 'Validation failed'
To make this work, follow those 3 steps:
Step 1
Mark Scenarios you expect exceptions in with some tag, e.g. @CatchException
:
@CatchException
Scenario: ...
Step 2
Define an AfterStep
handler to change ScenarioContext.TestStatus
to be OK
. You may only want ignore errors in for When steps, so you can still fail a test in Then verifying an exception. Had to do this through reflection as TestStatus
property is internal:
[AfterStep("CatchException")]
public void CatchException()
{
if (ScenarioContext.Current.StepContext.StepInfo.StepDefinitionType == StepDefinitionType.When)
{
PropertyInfo testStatusProperty = typeof(ScenarioContext).GetProperty("TestStatus", BindingFlags.NonPublic | BindingFlags.Instance);
testStatusProperty.SetValue(ScenarioContext.Current, TestStatus.OK);
}
}
Step 3
Validate TestError
the same way you would validate anything within ScenarioContext
.
[Then(@"Exception thrown with type '(.*)' and message '(.*)'")]
public void ThenExceptionThrown(string type, string message)
{
Assert.AreEqual(type, ScenarioContext.Current.TestError.GetType().Name);
Assert.AreEqual(message, ScenarioContext.Current.TestError.Message);
}
When
toThen
. – Phyllis