首先安裝Unit Test Generator。
方法為:工具->擴展和更新->聯機->搜索“圖標為裝有藍色液體的小試管。
Unit Test
Generator”,
編寫代碼,生成一個新的類,編寫構造函數 與 add()函數。代碼如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1_CXY
{
class Program
{
static void Main(string[] args)
{
}
}
public class test
{
public test(){
}
public int add(int a,int b)
{
return a + b;
}
}
}
在addTest()函數里編寫測試代碼,代碼如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication1_CXY;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ConsoleApplication1_CXY.Tests
{
[TestClass()]
public class testTests
{
[TestMethod()]
public void addTest()
{
int a=2,b=5,expect=7;
test t = new test();
int real = t.add(a,b);
Assert.AreEqual(real,expect);
//Assert.Fail();
}
}
}
測試結果如圖所示:

如此就完成了一個簡單的c#測試。
