您无法访问TestResult
对象,TestCleanup
因为它在此阶段尚不存在。在测试执行期间花费的时间TestCleanup
并TestInitialize
结合到TestResult.Duration
财产中。您可以通过以下方式轻松测试它:
[TestCleanup]
public void TestCleanup()
{
Thread.Sleep(1000);
}
在你的快速执行TestMethod
中。或者您可以检查Invoke
方法TestMethodInfo
:https ://github.com/microsoft/testfx/blob/167533cadfd2839641fc238d39ad2e86b4262be1/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs#L127
此方法将运行您的测试。您可以看到watch.Start()
和watch.Stop()
放置在哪里,以及ExecuteInternal
方法在哪里执行。此方法将在andRunTestInitializeMethod
和RunTestCleanupMethod
之间运行。Start
Stop
您唯一的解决方案是将测试类中的所有 TestResult 组合起来,然后在 ClassCleanup 方法中访问它们。
您可以通过实现自己TestMethodAttribute
的方法并覆盖Execute
方法来做到这一点。然后,您可以将所有结果保存在静态属性中 -Results
在TestResultCollection
类中 - 并在TestCleanup
方法中访问它。这是一个小例子:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace UnitTestProject
{
[TestClass]
public class UnitTest
{
[ClassCleanup]
public static void ClassCleanUp()
{
// Save TestResultCollection.Results in csv file
}
[MyTestMethod]
public void TestMethod()
{
Assert.IsTrue(true);
}
}
public static class TestResultCollection
{
public static Dictionary<ITestMethod, TestResult[]> Results { get; set; } = new Dictionary<ITestMethod, TestResult[]>();
}
public class MyTestMethodAttribute : TestMethodAttribute
{
public override TestResult[] Execute(ITestMethod testMethod)
{
TestResult[] results = base.Execute(testMethod);
TestResultCollection.Results.Add(testMethod, results);
return results;
}
}
}
请记住,这更像是一种 hack,而不是一个适当的解决方案。最好的选择是实现您自己的 csv 记录器并vstest.console.exe
使用csv
开关运行它。