我试图创建一个简单的装饰器,当测试失败时会截取屏幕截图。
我将以下内容用作基类,因此可以轻松引用与测试相关联的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
}
}
请帮我弄清楚如何从方法装饰器访问包含类。
答案 0 :(得分:2)
看起来细节包含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;
}
}