0

我想在 TestCleanup() 中使用 TestResult 来获取有关测试的一些信息。但我不知道如何初始化 TestResult 对象并获取它。我想要与 TestContext 对象相同的行为。

谢谢

    private static TestContext _testContext;
    [ClassInitialize]
    public static void SetupTests(TestContext testContext)
    {
        _testContext = testContext;
    }

编辑:因此,如果我无法在 TestCleanup 中访问 TestResult,如何在所有测试完成后将所有测试结果写入 csv 文件?

4

2 回答 2

3

您无法访问TestResult对象,TestCleanup因为它在此阶段尚不存在。在测试执行期间花费的时间TestCleanupTestInitialize结合到TestResult.Duration财产中。您可以通过以下方式轻松测试它:

[TestCleanup]
public void TestCleanup()
{
    Thread.Sleep(1000);
}

在你的快速执行TestMethod中。或者您可以检查Invoke方法TestMethodInfohttps ://github.com/microsoft/testfx/blob/167533cadfd2839641fc238d39ad2e86b4262be1/src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs#L127

此方法将运行您的测试。您可以看到watch.Start()watch.Stop()放置在哪里,以及ExecuteInternal方法在哪里执行。此方法将在andRunTestInitializeMethodRunTestCleanupMethod之间运行。StartStop

您唯一的解决方案是将测试类中的所有 TestResult 组合起来,然后在 ClassCleanup 方法中访问它们。

您可以通过实现自己TestMethodAttribute的方法并覆盖Execute方法来做到这一点。然后,您可以将所有结果保存在静态属性中 -ResultsTestResultCollection类中 - 并在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开关运行它。

于 2019-06-15T13:48:48.470 回答
0

TestResult 对象的数组由 TestMethod 属性返回给适配器。这不是您可以访问的。您将需要从 TestContext 获取您的信息。

https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.testmethodattribute?view=mstest-net-1.2.0

https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.testresult?view=mstest-net-1.2.0

于 2019-06-14T14:23:57.700 回答