visual studio单元测试
测试代码:
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] public class 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:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构