StoryQ场景,预计会出现异常

我们如何使用StoryQ来测试预期Exception的场景?     
已邀请:

bab

就实际代码而言,在测试代码的
.Then
部分中,您需要创建一个
Action
Func
来确定正在测试的内容,然后在代码的
.Then
部分中,您将调用该代码并进行测试结果。例如:
[Test]
public void AnIllegalOperationThrowsAnException()
{
    new Story("My Story)
        .InOrderTo("Do achieve something")
        .AsA("User")
        .IWant("To carry out an operation")
        .WithScenario("an exception occurs")
        .Given(InitialConditions)
        .When(TheIllegalActionIsTaken)
        .Then(AnIllegalOperationExceptionIsThrown);
}

private void InitialConditions()
{
}

private Func<string> _operation;

private void TheIllegalActionIsTaken()
{
    _operation = () => return MyTestClass.DoesSomethingWrong();
}

private void AnIllegalOperationExceptionIsThrown()
{
    try
    {
        _operation.Invoke();
        Assert.Fail("An exception should have been thrown");
    }
    catch (Exception ex)
    {
        Assert.That(ex, Is.InstanceOf<IllegalOperationException>(), "The wrong exception was thrown");
        Assert.That(ex.Message, Is.EqualTo("Ooops!");
    }
}
断言处理可能会稍微整理一下,尤其是测试方法不返回值。例如,FluentAssertions库可以很好地与Action(但不是Func)一起工作,因此代码将是:
_action.ShouldThrow<IllegalOperationException>().WithMessage("Ooops!");
    
BDD场景框架从用户的角度描述了系统的行为。抛出异常时用户会看到什么?一个消息?一个消息框? 如果您可以弄清楚如何看到异常,它可能会帮助您编写方案。     

要回复问题请先登录注册