Version: 6000.3
语言: 中文
15. 测试用例
17. 以编程方式运行测试

16. 自定义属性

学习目标

在本节中,我们将介绍一些实现自定义 NUnit 属性的方法,这些属性可用于更改测试执行。

介绍和动机

NUnit 的一个强大部分是它非常可扩展。扩展它的方法之一是通过自定义属性。一个示例是实现 IWrapTestMethod 接口的属性。此接口有一个用于包装TestCommand,它实现了一个执行方法。通常,这些测试命令会执行某些作,在其内部命令上调用 execute,然后在内部命令完成后可能再次执行某些作。

在以下三个类中,一个IWrapTestMethod接口在测试中实现和使用:

public class MyAttribute : NUnitAttribute, IWrapTestMethod
{
 public TestCommand Wrap(TestCommand command)
 {
  return new MyCommand(command);
 }
}

public class MyCommand : TestCommand
{
 private TestCommand innerCommand;
 
 public MyCommand(TestCommand command) : base(command.Test)
 {
  innerCommand = command;
 }

 public override TestResult Execute(ITestExecutionContext context)
 {
  Debug.Log("Before");
  var result = innerCommand.Execute(context);
  Debug.Log("After");

  return result;
 }
}

public class MyTests
{
 [Test]
 [MyAttribute]
 public void Test1()
 {
  Debug.Log("The test");
 }
}

运行时MyTests.Test1将打印以下输出:

测试 1 (0,017s)
-–
测试

测试后

自定义属性可以实现的其他接口包括IWrapSetUpTearDown,IApplyToContextIApplyToTest.

锻炼

在 Unity,我们的目标是作时间不应超过 500 毫秒。在示例 16_CustomAttributes有一个叫做MyClass,它有两个方法。两种方法都应该返回 true。但是,有人进行了回归,因此两种方法中的一种需要很长时间才能运行。

任务是创建一个新的自定义属性,该属性检测测试运行时间是否超过 500 毫秒。如果发生这种情况,它应该会使测试失败,并显示一条描述性消息。将其应用于两个现有测试。

提示

  • 您可以使用类System.Diagnostics.Stopwatch计时已经过去了多少毫秒。

溶液

该练习的完整解决方案可在以下网址获得:16_CustomAttributes_Solution.

该解决方案的核心是测试命令实现中的 execute 方法:

public override TestResult Execute(ITestExecutionContext context)
{
 var stopWatch = new Stopwatch();
 stopWatch.Start();
 var result = innerCommand.Execute(context);
 stopWatch.Stop();

 if (stopWatch.ElapsedMilliseconds > 500)
 {
  result.SetResult(ResultState.Failure, $"Test took {stopWatch.ElapsedMilliseconds} ms. That is longer than 500ms!");
 }

 return result;
}
15. 测试用例
17. 以编程方式运行测试