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待学习.... } }