我的解决方案涉及到几个项目来实现的,但在最后它看起来更优雅:
@CatchException
Scenario: Faulty operation throws exception
Given Some Context
When Some faulty operation invoked
Then Exception thrown with type 'ValidationException' and message 'Validation failed'
为了使这项工作,遵循这些3个步骤:
第1步
标记您预计某些标记出现异常的场景,例如@CatchException
:
@CatchException
Scenario: ...
步骤2
定义一个AfterStep
处理程序改变ScenarioContext.TestStatus
是OK
。您可能只想忽略错误当步骤,所以你仍然可以通过测试失败,然后验证异常。已通过反射来做到这一点作为TestStatus
属性是内部:
[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);
}
}
步骤3
验证TestError
你会内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);
}
嘿,你有没有发现这些答案有用? – 2011-09-28 00:22:43
@scoarescoare:是的。问题是,包含所有必需信息的正确答案是您和Kjetil的组合。你的回答说我的语言是错误的,而Kjetil实际上是说如何从'When'到Then的异常(或其他输出)。 – 2011-09-28 08:05:17
感谢您提出这个问题。我发现自己想知道同样的事情! – 2015-09-03 11:03:00