且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在 MStest 中执行完所有测试后运行代码

更新时间:2023-02-20 20:43:13

是的,这是可能的.为此,您可以使用 AssemblyCleanup 属性:

Yes it is possible. You can use the AssemblyCleanup Attribute for this purpose:

标识包含要在所有测试之后使用的代码的方法程序集已运行并释放程序集获得的资源.

Identifies a method that contains code to be used after all tests in the assembly have run and to free resources obtained by the assembly.

以下是根据执行时间排列的所有 MSTest 方法的概述:

Here is an overview of all MSTest methods arranged according to execution time:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using SampleClassLib;
using System;
using System.Windows.Forms;

namespace TestNamespace
{
    [TestClass()]
    public sealed class DivideClassTest
    {
        [AssemblyInitialize()]
        public static void AssemblyInit(TestContext context)
        {
            MessageBox.Show("AssemblyInit " + context.TestName);
        }

        [ClassInitialize()]
        public static void ClassInit(TestContext context)
        {
            MessageBox.Show("ClassInit " + context.TestName);
        }

        [TestInitialize()]
        public void Initialize()
        {
            MessageBox.Show("TestMethodInit");
        }

        [TestCleanup()]
        public void Cleanup()
        {
            MessageBox.Show("TestMethodCleanup");
        }

        [ClassCleanup()]
        public static void ClassCleanup()
        {
            MessageBox.Show("ClassCleanup");
        }

        [AssemblyCleanup()]
        public static void AssemblyCleanup()
        {
            MessageBox.Show("AssemblyCleanup");
        }

        [TestMethod()]
        [ExpectedException(typeof(System.DivideByZeroException))]
        public void DivideMethodTest()
        {
            DivideClass.DivideMethod(0);
        }
    }
}

请参阅:MSTest-Methods