单元测试入门学习(读 农码一生 博客)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestDemo { public class Arithmetic { public int Add( int nb1, int nb2) { return nb1 + nb2; } public int Divide( int nb1, int nb2) { if (nb2 == 0) { throw new Exception( "除数不能为零" ); } return nb1 / nb2; } } } |
测试类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace TestDemo.Tests { public class Arithmetic_Tests { //依赖: // XUnit 2.2.0 单元测试框架 // xunit.runner.visualstudio 2.2.0 测试运行工具 // Moq 4.7.10 模拟框架 //[Fact]//需要在测试方法加上特性Fact 和 Theory不能一起用 [Fact]//需要在测试方法加上特性Fact public void Add_Ok() { Arithmetic arithmetic = new Arithmetic(); var sum = arithmetic.Add(1, 2); Assert.True(sum == 3);//断言验证 } [Theory] [InlineData(2, 3, 5)] [InlineData(2, 4, 6)] [InlineData(2, 1, 4)] //对应测试方法的形参 public void Add_Ok(int nb1, int nb2, int result) { Arithmetic arithmetic = new Arithmetic(); var sum = arithmetic.Add(nb1, nb2); Assert.True(sum == result);//断言验证 } //[Theory] //[InlineData(2, 3, 0)] //[InlineData(2, 4, 0)] //[InlineData(2, 1, 0)] //public void Add_No(int nb1, int nb2, int result) //{ // Arithmetic arithmetic = new Arithmetic(); // var sum = arithmetic.Add(nb1, nb2); // Assert.False(sum == result); //} [Fact] public void Divide_Err() { Arithmetic arithmetic = new Arithmetic(); Assert.Throws<Exception>(() => { arithmetic.Divide(4, 0); });//断言 验证异常 } //MOQ待学习.... } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
2016-05-18 读写app.config AppSettings,保留注释与不保留注释