C# 当使用Nunit操作属性时,如何访问测试方法的实例类?
我正在尝试创建一个简单的装饰器,当测试失败时,它会截图 我将以下内容用作基类,因此有一个与测试相关联的webdriver的易于引用的实例C# 当使用Nunit操作属性时,如何访问测试方法的实例类?,c#,selenium,nunit,decorator,C#,Selenium,Nunit,Decorator,我正在尝试创建一个简单的装饰器,当测试失败时,它会截图 我将以下内容用作基类,因此有一个与测试相关联的webdriver的易于引用的实例 public class SeleniumBaseTest { public IWebDriver Driver; public IWebDriver NewWebdriver() { Driver = WebDriverFactory.NewDriver(); return Driver; }
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
}
}
请帮助我找出如何从方法装饰器访问包含类。详细信息似乎包含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;
}
}
尽管如此,我仍然想知道如何为我想编写的其他几个装饰器访问装饰方法的上下文。