C#中进行单元测试

时间:2023-03-08 21:52:00

首先创建一个项目,写一段待测的程序:

namespace ForTest
{
public class Program
{
static void Main(string[] args)
{
}
public int Say(int a, int b)
{
if (a < && b > )
{
return a + b;
}
else
{
return a;
}
}
}
}

然后鼠标右键点击Say函数,选择Create Unit Tests,这里我写了两个case:

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ForTest.Tests
{
[TestClass()]
public class ProgramTests
{
[TestMethod()]
public void SayTest()
{
Program p = new Program();
int a = ;
int b = ;
int c = p.Say(a, b);
Assert.AreEqual(c, a + b);
} [TestMethod()]
public void SayTest1()
{
Program p = new Program();
int a = ;
int b = ;
int c = p.Say(a, b);
Assert.AreEqual(c, a);
}
}
}

然后鼠标右键点击测试方法(或者测试类),选择Run Tests就开始跑case了:

C#中进行单元测试

这样一个简单的单元测试就完成了。

我们可以根据待测程序来设计测试数据,确保程序中每个分支路径都覆盖到。以上只是举个例子。