编码的 UI 在失败断言时继续



嗨,我知道其他人之前已经问过我要问的问题,但我仍然不清楚那些已经在网上发布的问题,因此我发布这个问题来澄清我的疑问。希望你们能帮我解决。

目前我正在使用Microsoft Visual Studio 2013 Premium。我正在使用录制和播放功能。我记录了一些动作和一些验证点。现在,当验证点失败时,脚本将立即停止。但是,我希望脚本继续运行,即使某些点失败了。我在网上读到了一些选项,但我不知道应该将它们放在我的脚本中的位置。我看到了这篇文章 编码的UI - 断言的"失败时继续" 但是我没有使用 SpecFlow 这仍然适用于我吗?另外,我应该将这些代码放在哪个部分?在我的方法里面?创建新方法?或?

bool thisTestFailed = false;
if ( ... the first assertion ... ) { thisTestFailed = true; }
if ( ... another assertion ... ) { thisTestFailed = true; }
if ( ... and another assertion ... ) { thisTestFailed = true; }
if ( thisTestFailed ) {
Assert.Fail("A suitable test failed message");
}"

断言并不意味着使用 Assert.SomeCondition() 。只需使用简单的条件来设置thisTestFailed。Assert 类抛出一个AssertFailedException来表示失败。不应捕获此异常。此异常由单元测试引擎处理,以指示断言失败。

bool thisTestFailed = false;
if ( {someCondition} ) { thisTestFailed = true; }
if ( !{someOtherConditionWhichShouldBeFalse} ) { thisTestFailed = true; }
if ( {yetAnotherCondition} ) { thisTestFailed = true; }
if ( thisTestFailed ) {
    Assert.Fail("A suitable test failed message");
}"

甚至更容易:

bool thisTestFailed = {someCondition} ||
 !{someOtherConditionWhichShouldBeFalse} ||
 {yetAnotherCondition}
Assert.IsFalse(thisTestFailed, "A suitable test failed message");

这样,您可以获得所有"测试",但只有一个Assert.Fail.

链接的问题确实提到了 Specflow,但问题的细节和接受的答案并不依赖于 Specflow。

通常,由编码的 UI 记录和生成的断言方法有点像:

void AssertionMethod1()
{
    ... get the values of fieldOne, fieldTwo, etc
    Assert.Equals(fieldOne, fieldOneExpectedValue);
    Assert.Equals(fieldTwo, fieldTwoExpectedValue);
    Assert.Equals(fieldThree, fieldThreeExpectedValue);
    ... more calls of assert methods.
}

使用的断言方法和访问字段值的机制可能会更复杂。

每个Assert.Equals(...)都是使用类似于以下内容的代码实现的:

void Assert.Equals(string actual, string expected)
{
    if ( actual == expected )
    {
        // Pass. Nothing more to do.
    }
    else
    {
        // Fail the test now.
        throw AnAssertionFailureException(...);
    }
}

因此,链接的问题建议将调用更改为记录的断言方法(即从CodedUItestMethod1调用AssertionMethod1)如下:

... get the values of fieldOne, fieldTwo, etc
if(fieldOne != fieldOneExpectedValue) { thisTestFailed = true; }
if(fieldTwo != fieldTwoExpectedValue) { thisTestFailed = true; }
if(fieldThree != fieldThreeExpectedValue) { thisTestFailed = true; }
... etc.

尽管更简单的方法是将AssertionMethod1复制到另一个文件中,然后将其修改为如上所述。编码的 UI 中的 UIMap 编辑器具有"将代码移动到 UIMap.cs"命令(通过上下文菜单或命令图标访问),该命令将方法移动到uimap.cs文件中,从而允许您根据需要对其进行编辑。自动生成的代码将进入uimap.designer.cs文件,不应编辑此文件。它和uimap.cs文件都在其顶部附近partial class UIMap,因此它们的组合内容构成了类。uimap.cs文件用于添加到 UI 映射。

最新更新