在拆解中未通过NUnit测试

时间:2015-12-22 00:52:12

标签: c# selenium nunit

我有一系列使用selenium和NUnit运行的自动化UI测试。

在每次nunit测试后,我想检查浏览器是否有任何已发生的JS错误。如果存在任何JS错误,则导致它们的测试将失败。我希望这可以运行我编写的所有测试,而无需将检查复制到每个测试中。

我也会在任何失败时截取屏幕截图。

    [TearDown]
    public void TearDown()
    {
        Assert.Fail("Some JS error occurred"); //This is to simulate a JS error assertion

        if (TestContext.CurrentContext.Result.Status != TestStatus.Passed)
        {
            Driver.TakeScreenshot(TestContext.CurrentContext.Test.Name, "Failed");
        }
    }

如果我在拆解内部失败,它将永远不会执行屏幕截图代码(因为断言是一个例外)。

有没有更好的方法让测试失败,以便继续我的逻辑?

2 个答案:

答案 0 :(得分:2)

您可以扩展自己运行JS测试的TestActionAttribute。如果在AfterTest()中抛出断言失败,NUnit似乎会将测试报告为失败。

E.g。这样:

[CheckForJSErrors] // your custom attribute - applies to all tests
public class ClassTest
{
    [Test]
    public void MyTest()
    {
        // Your test case
    }
}

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class CheckForJSErrorsAttribute : TestActionAttribute
{
    public override void AfterTest(TestDetails testDetails)
    {
        // if you only want to check for JS errors if the test passed, then:
        if(TestContext.CurrentContext.Result.Status == TestStatus.Passed)
        {
            Driver.TakeScreenshot(testDetails.FullName, "Failed");
            Assert.Fail("Some JS error occurred"); //This is to simulate a JS error assertion
        }
    }
    public override ActionTargets Targets
    {
        // explicitly says to run this after each test, even if attr is defined on the entire test fixture
        get { return ActionTargets.Test; }
    }
}

在NUnit中产生此故障:

SO_34306757.ClassTest.MyTest: TearDown : NUnit.Framework.AssertionException : Some JS error occurred

我已经为整个测试夹具声明了[CheckForJSErrors]属性,以避免在每个测试用例中声明它,但如果需要,可以按照测试方法声明它。

答案 1 :(得分:0)

如果你想在每次测试后检查相同的东西,你可以选择在每个测试中调用的常用方法。这样你就不会复制测试代码了,你就会把失败断言保留在拆除状态之外。

例如

[Test]
public void Test1()
{
    // sometest code
    TestJS();
}

[Test]
public void Test2()
{
    // some other test code
    TestJS();
}

public void TestJS()
{
    Assert.Fail("Or whatever to test the JS");
}

[TearDown]
public void TearDown()
{
    if (TestContext.CurrentContext.Result.Status != TestStatus.Passed)
    {
        Driver.TakeScreenshot(TestContext.CurrentContext.Test.Name, "Failed");
    }
}
相关问题