【问题标题】:How to access instance class of a test method when using Nunit action attributes?使用 Nunit 动作属性时如何访问测试方法的实例类?
【发布时间】:2014-04-14 18:26:11
【问题描述】:

我正在尝试创建一个简单的装饰器,它会在测试失败时截屏。

我将以下内容用作基类,因此有一个易于引用的与测试关联的 webdriver 实例。

public class SeleniumBaseTest {
    public IWebDriver Driver;

    public IWebDriver NewWebdriver() {
       Driver = WebDriverFactory.NewDriver();
       return Driver;
    }

    public void TakeScreenShot() { 
        //code to take screenshot.
    }
}

到目前为止,我已经能够创建一个装饰器来在测试失败后执行操作。但是我还没有弄清楚如何获取当前的测试类实例,以便我可以获取关联的 webdriver。

[AttributeUsage(AttributeTargets.Method)]
public class ScreenShotOnError: Attribute, ITestAction
{

    public void BeforeTest(TestDetails details)
    {
        // do nothing
    }

    public void AfterTest(TestDetails details)
    {
        switch (TestContext.CurrentContext.Result.Status)
        {
            case TestStatus.Failed:
            case TestStatus.Inconclusive:
                var context = TestContext.CurrentContext;
                Console.WriteLine("Test failed hook running.");
                Console.WriteLine(context);
                // I need to figure out how to access the test instance.
                // _SeleniumBaseTestInstance.TakeScreenShot();
                break;
        }
    }


    public ActionTargets Targets
    {
        get { return ActionTargets.Test; }
    }
}

这个基础测试和装饰器的使用就像,

[TestFixture]
class FtwWebScreenShotTestActionTest:SeleniumBaseTest 
{

    [Test]        
    [ScreenShotOnError]
    public void Test()
    {
        var driver = NewWebdriver();
        // perform test actions
    }

}

请帮我弄清楚如何从方法装饰器访问包含类。

【问题讨论】:

    标签: c# selenium nunit decorator


    【解决方案1】:

    看起来细节包含 TestFixture,这是我想要的类的实例。

     public void AfterTest(TestDetails details)
            {
                switch (TestContext.CurrentContext.Result.Status)
                {
                    case TestStatus.Failed:
                    case TestStatus.Inconclusive:
                        try
                        {
                            (details.Fixture as SeleniumBaseTest).TakeScreenShot();
                        }
                        catch (NullReferenceException)
                        {
                            throw new TypeAccessException("This decorator should only be used with {0}" + typeof(SeleniumBaseTest).Name);
                        }
                        break;
                }
            }
    

    【讨论】:

    • 尽管如此,我仍然想知道如何为我想编写的其他一些装饰器访问装饰方法的上下文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多