Tom*_*ski 8 .net c# selenium nunit unit-testing
你们有没有人知道在测试失败和例外情况下截图的可能解决方案?
我已经添加了以下代码,TearDown()但因此它也会对通过的测试进行截图,因此它不是最佳解决方案:
DateTime time = DateTime.Now;
string dateToday = "_date_" + time.ToString("yyyy-MM-dd") + "_time_" + time.ToString("HH-mm-ss");
Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile((settings.filePathForScreenShots + "Exception" + dateToday + ".png"), System.Drawing.Imaging.ImageFormat.Png);
Run Code Online (Sandbox Code Playgroud)
我已经找到了这个想法:http://yizeng.me/2014/02/08/take-a-screenshot-on-exception-with-selenium-csharp-eventfiringwebdriver/,使用WebDriverExceptionEventArgs,但由于某些原因,它使还有一些随机的截图,没有任何合理的解释.
我发现的其他想法是针对Java的,而不是我用于Selenium的NUnit,所以它们都没用.
Eri*_*ebo 12
如果将屏幕截图逻辑放在TearDown方法中,则会在每次测试完成后调用它,无论它是成功还是失败.
我使用一个基类,它具有包装测试的函数并捕获所有异常.当测试失败时,将捕获异常并截取屏幕截图.
我在所有的Selenium测试中使用这个基类,它看起来像这样:
public class PageTestBase
{
protected IWebDriver Driver;
protected void UITest(Action action)
{
try
{
action();
}
catch (Exception ex)
{
var screenshot = Driver.TakeScreenshot();
var filePath = "<some appropriate file path goes here>";
screenshot.SaveAsFile(filePath, ImageFormat.Png);
// This would be a good place to log the exception message and
// save together with the screenshot
throw;
}
}
}
Run Code Online (Sandbox Code Playgroud)
测试类看起来像这样:
[TestFixture]
public class FooBarTests : PageTestBase
{
// Make sure to initialize the driver in the constructor or SetUp method,
// depending on your preferences
[Test]
public void Some_test_name_goes_here()
{
UITest(() =>
{
// Do your test steps here, including asserts etc.
// Any exceptions will be caught by the base class
// and screenshots will be taken
});
}
[TearDown]
public void TearDown()
{
// Close and dispose the driver
}
}
Run Code Online (Sandbox Code Playgroud)
Luk*_*kas 10
在C#中我使用NUnit 3.4.这提供了OneTimeTearDown能够访问TestContext包括先前执行的测试的状态的方法.不要使用,TearDown因为它在测试失败后没有执行;)
using OpenQA.Selenium;
using System.Drawing.Imaging;
...
[OneTimeTearDown]
public void OneTimeTearDown()
{
if (TestContext.CurrentContext.Result.Outcome != ResultState.Success)
{
var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile(@"C:\TEMP\Screenshot.jpg", ImageFormat.Jpeg);
}
}
Run Code Online (Sandbox Code Playgroud)
为了更加公正,这里是 MSTest 的代码
public TestContext TestContext { get; set; }
[TestCleanup]
public void TestCleanup()
{
if (TestContext.CurrentTestOutcome == UnitTestOutcome.Failed)
{
var screenshotPath = $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss.fffff}.png";
MyDriverInstance.TakeScreenshot().SaveAsFile(screenshotPath);
TestContext.AddResultFile(screenshotPath);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16498 次 |
| 最近记录: |