Last active
December 3, 2025 14:23
-
-
Save zhaopan/7aaa2a8f38b6acfeb083c17608889b93 to your computer and use it in GitHub Desktop.
UnitTest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.IO; | |
| using Microsoft.VisualStudio.TestTools.UnitTesting; | |
| namespace MyTests | |
| { | |
| [TestClass] | |
| public class UnitTest1 | |
| { | |
| private const string LogFileName = "TestOutputLog.txt"; | |
| private static StreamWriter? _logWriter; | |
| /// <summary> | |
| /// Test.txt 运行结果顺序: | |
| /// MyClassInitialize | |
| /// MyTestInitialize | |
| /// TestMethod2 | |
| /// MyTestCleanup | |
| /// MyTestInitialize | |
| /// TestMethod3 | |
| /// MyTestCleanup | |
| /// MyTestInitialize | |
| /// TestMethod1 | |
| /// MyTestCleanup | |
| /// MyClassCleanup | |
| /// </summary> | |
| [ClassInitialize(InheritanceBehavior.BeforeEachDerivedClass)] | |
| public static void MyClassInitialize(TestContext testContext) | |
| { | |
| string logFilePath = Path.Combine(testContext.TestRunResultsDirectory ?? AppDomain.CurrentDomain.BaseDirectory, LogFileName); | |
| try | |
| { | |
| _logWriter = new StreamWriter(logFilePath, false); | |
| _logWriter.WriteLine("MyClassInitialize"); | |
| _logWriter.Flush(); | |
| } | |
| catch (Exception ex) | |
| { | |
| testContext.WriteLine($"Error during ClassInitialize: {ex.Message}"); | |
| _logWriter?.Dispose(); | |
| _logWriter = null; | |
| Assert.Inconclusive($"Failed to initialize log file at {logFilePath}: {ex.Message}"); | |
| } | |
| } | |
| [ClassCleanup()] | |
| public static void MyClassCleanup() | |
| { | |
| if (_logWriter == null) return; | |
| _logWriter.WriteLine("MyClassCleanup"); | |
| _logWriter.Flush(); | |
| _logWriter.Dispose(); | |
| _logWriter = null; | |
| } | |
| [TestInitialize()] | |
| public void MyTestInitialize() | |
| { | |
| _logWriter?.WriteLine("MyTestInitialize"); | |
| _logWriter?.Flush(); | |
| } | |
| [TestCleanup()] | |
| public void MyTestCleanup() | |
| { | |
| _logWriter?.WriteLine("MyTestCleanup"); | |
| _logWriter?.Flush(); | |
| } | |
| [TestMethod] | |
| public void TestMethod1() | |
| { | |
| _logWriter?.WriteLine("TestMethod1"); | |
| _logWriter?.Flush(); | |
| } | |
| [TestMethod] | |
| public void TestMethod2() | |
| { | |
| _logWriter?.WriteLine("TestMethod2"); | |
| _logWriter?.Flush(); | |
| } | |
| [TestMethod] | |
| public void TestMethod3() | |
| { | |
| _logWriter?.WriteLine("TestMethod3"); | |
| _logWriter?.Flush(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment