visual studio單元測試
阿新 • • 發佈:2022-04-13
測試程式碼:
class Cmp { public int Largest(int[] list) { if (list.Length == 0) throw new ArgumentException("Empty list"); int index, max = Int32.MinValue; for (index = 0; index < list.Length; index++) {if (list[index] > max) max = list[index]; } return max; } }
測試步驟:
1.新建測試專案
2. 新建Cmp類,將測試程式碼放進去
3.在測試類中編寫測試用例
程式碼:
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProject2 { [TestClass] publicclass UnitTest1 { Cmp cmp = new Cmp(); [TestMethod] public void TestMethod1() { int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int t1 = cmp.Largest(test1); Assert.AreEqual<Int32>(t1, 9); } [TestMethod]public void TestMethod2() { int[] test2 = { 2, 2, 2, 2, 2, 2, 2, 2, 2 }; int t2 = cmp.Largest(test2); Assert.AreEqual<Int32>(t2, 2); } [TestMethod] public void TestMethod3() { int[] test3 = { -1, -8, -9, -6, 5, 7, 3, 4, -6 }; int t3 = cmp.Largest(test3); Assert.AreEqual<Int32>(t3, 7); } [TestMethod] public void TestMethod4() { int[] test4 = { 0, 0, 0 }; int t4 = cmp.Largest(test4); Assert.AreEqual<Int32>(t4, 0); } [TestMethod] public void TestMethod5() { int[] test5 = { }; int t5 = cmp.Largest(test5); Assert.Fail(); } } }
4.執行測試(右擊執行測試)
4.檢視程式碼覆蓋率
TestMethod1:
TestMethod2:
TestMethod3:
TestMethod4:
TestMethod5: