MS Test也可以方便的进行单元测试,可以通过Visual Studio很方便的建立单元测试。
添加对待测试工程的引用,即可方便的开始单元测试。
最基本的一些测试使用如下:
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { } [ClassInitialize] public static void Init(TestContext context) { Console.WriteLine("Use ClassCleanup to run code before all tests in a class have run."); } [TestInitialize] public void BeforeTest() { Console.WriteLine("Use TestCleanup to run code before you run each test."); } [TestMethod] public void TestAMethodOrFunction() { Assert.AreEqual(3, 3); } [TestCleanup] public void AfterTest() { Console.WriteLine("Use TestCleanup to run code after you run each test."); } [ClassCleanup] public static void Cleanup() { Console.WriteLine("Use ClassCleanup to run code after all tests in a class have run."); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestExpectedException() { throw new ArgumentException("Wrong argument!"); } } }
其中的标签的作用和NUnit类似,只是名称稍有不同。不做过多解释。
可以通过Visual Studio 的Test菜单,运行进行有关测试的一些操作,如运行指定测试、运行所有测试、查看覆盖率。。。
例如,我们针对如下一个单元测试通过Test菜单运行所有测试如下:
也可以在Test Explorer中控制测试的运行,如
分析代码覆盖率,等等等等