问题描述
我正在使用NUNIT的Visual Studio中使用Selenium Webdriver.测试用例的代码是
I am using selenium webdriver in visual studio Using NUNIT. The code of test case is
我想在测试用例执行后立即记录测试用例是否通过或失败,如何实现?
I want to Log that test case is passed or fail in a variable right after the test case is executed.How can I achieve that?
推荐答案
NUnit
假设您使用NUnit(因为问题看起来像MSTest),则可以编写自定义 IWrapTestMethod
属性以扩展测试命令.该属性使您有机会在每次测试运行之前和之后检查测试和测试结果:
NUnit
Assume you use NUnit (because what's in the question looks like MSTest), you could write custom IWrapTestMethod
attribute to extend the test command. The attribute gives you an opportunity to inspect on the test and test result before and after each test run:
// I don't know where your variable is, so just use this dummy class with
// some dummy static properties.
class TestResultKeeper
{
public static TestResult TestResult { get; set; }
public static ResultState ResultState => TestResult?.ResultState ?? ResultState.Failure;
public static bool IsPassed => ResultState == ResultState.Success;
public static Exception Exception { get; set; }
}
// Custom NUnit 3 attribute to extend test method
public class LogTestAttribute : Attribute, IWrapTestMethod
{
public TestCommand Wrap(TestCommand command)
{
// Wrap test command
return new LogTestResultCommand(command);
}
}
class LogTestResultCommand : DelegatingTestCommand
{
public LogTestResultCommand(TestCommand innerCommand)
: base(innerCommand)
{
}
public override TestResult Execute(TestExecutionContext context)
{
try
{
var result = innerCommand.Execute(context);
// Set test result to TestResultKeeper
TestResultKeeper.TestResult = result;
TestResultKeeper.Exception = null;
return result;
}
catch (Exception e)
{
// Exception thrown from test. Test failed.
TestResultKeeper.TestResult = null;
TestResultKeeper.Exception = e.InnerException;
throw;
}
}
}
用法:
[Test, LogTest]
public void Test1()
{
Assert.Fail();
}
[Test, LogTest]
public void Test2()
{
Assert.Pass();
}
MSTest
假设您的测试是用MSTest编写的(按照您的示例),则可以创建新的测试方法属性并从TestMethodAttribute
派生,并执行与上述类似的操作:
MSTest
Assume your test is written in MSTest (as per your example), you could create a new test method attribute and derive from TestMethodAttribute
, and do similar things as above:
class TestResultKeeper
{
public static TestResult TestResult { get; set; }
public static UnitTestOutcome TestOutcome => TestResult?.Outcome ?? UnitTestOutcome.Failed;
public static bool IsPassed => TestOutcome == UnitTestOutcome.Passed;
public static Exception Exception { get; set; }
}
public class LogTestTestMethodAttribute : TestMethodAttribute
{
public override TestResult[] Execute(ITestMethod testMethod)
{
var testResult = base.Execute(testMethod)[0];
TestResultKeeper.TestResult = testResult;
TestResultKeeper.Exception = testResult.TestFailureException;
return new[] { testResult };
}
}
用法:
[LogTestTestMethod]
public void TestMethod1()
{
}
这篇关于测试用例执行完成后,如何将测试用例结果保存在变量中,无论是否通过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!