在需要测试的解决方案中新建单元测试项目

在测试类中引用需要测试的项目引用编写测试方法

 1 using Microsoft.VisualStudio.TestTools.UnitTesting;
 2 using System;
 3 using System.IO;
 4 
 5 namespace UnitTestProject1
 6 {
 7     [TestClass]
 8     public class UnitTest1
 9     {
10         private const string Expected = "Hello World!";
11         [TestMethod]
12         public void TestMethod1()
13         {
14             using (var sw = new StringWriter())
15             {
16                 Console.SetOut(sw);
17                 HelloWorldCore.Program.Main();
18                 var result = sw.ToString().Trim();
19                 //判断结果是否与预期一致
20                 Assert.AreEqual(Expected, result);
21                 //判断是否能引发异常
22                 Assert.ThrowsException<Exception>(() => HelloWorldCore.Program.Main());
23             }
24         }
25         [TestMethod]
26         public void TestMethod2()
27         {
28             using (var sw = new StringWriter())
29             {
30                 Console.SetOut(sw);
31                 var result = HelloWorldCore.Program.SayGoodbye();
32                 Assert.AreEqual(Expected, result);
33             }
34         }
35     }
36 }

 

posted on 2021-02-02 14:26  小杰杰儿  阅读(91)  评论(0)    收藏  举报