C#培训2019-9-9第六课NUnit 实现函数(方法)的调试

NUnit
实际代码运行过程中,需要对各个分功能进行单独测试,保证单个函数(方法)的正确性,此时用到软件UNnit。
首先安装好软件(本次安装的是NUnit 2.7.1),打开Visual Studio 2008。
一、使用NUnit:
1、添加NUnit软件的动态链接库(nunit.framework.dll)
在Visual Studio右侧的“解决方案管理器”的“引用”下(没有“解决方案管理器”可以在视图下打开),右键添加→添加引用→浏览,找到路径:C:\Program Files (x86)\NUnit 2.7.1\bin\framework\nunit.framework.dll
2、新建一个类,用来写测试代码
在Visual Studio右侧的“解决方案管理器”的项目下右键→添加→新建项,选择“类”,修改名称确定。
3、在新建的类开头,添加“using NUnit.Framework;”

到这里,准备工作已经就绪,下面开始测试:

4、把需要测试的函数(方法)申明改成public,方便测试的类进行调用
如:

		static int[] GetUserInput(string szInputValue)
		{
		}
		//需要改为
		public static int[] GetUserInput(string szInputValue)
		{
		}

5、在测试类中新建一个方法,用来测试函数(方法)
如:

//申明时需要用 "public",方便NUnit程序调用
public int[] testGetUserInput( string szInput )
		{
			
		}

注意,方法名最好与被测试的方法相匹配,传入类型也要与被测试的方法匹配。

6、在新建的方法中添加返回值

public int[] testGetUserInput( string szInput )
		{
		//此时Program为被测试函数所属类的名称,当GetUserInput定义为public时,打出Program. 就有提示可以调用GetUserInput
			return Program.GetUserInput( szInput );
		}

7、在新建的方法上方添加测试代码
如:

		//"5638"为传入值,{ 8, 3, 6, 5 ,0}为应该传出的正确的数组。
		[TestCase( "5638", Result = new int[] { 8, 3, 6, 5 ,0} )]
		[TestCase( "0456", Result = new int[] { 6, 5, 4, 0 ,0} )]
		public int[] testGetUserInput( string szInput )
		{
			return Program.GetUserInput( szInput );
		}

注意,当传入/传出的为数组时,需要用new 来定义(?),给出数组的空间,来存放数值
例如:传入传出都是数组int[]

[TestCase( new int[] { 1, 2, 3 }, new int[] { 1, 0, 0 }, Result = new int[] { 2, 2, 3 ,0,0} )]

例如:传入传出都是int

		[TestCase( 4, 3, Result = 7)]

8、最后修改启动调试
在“项目”→“XXX属性”→“调试”→“启动操作”→“启动外部程序” 选择NUnit软件的启动目录如下
例如:C:\Program Files (x86)\NUnit 2.7.1\bin\nunit.exe

9、启动调试后会弹出NUnit软件界面,如下
C#培训2019-9-9第六课NUnit 实现函数(方法)的调试_第1张图片
点击左上角的File→OpenProject,打开所需要测试方法的解决方案调试时生成的可执行文件,如
D:\ArrayAdd\ArrayPractice9-5\bin\Debug\ArrayPractice9-5.exe
选择好后,点击中间上方的RUN,若正确则会显示绿色。
如:C#培训2019-9-9第六课NUnit 实现函数(方法)的调试_第2张图片
10、NUnit 支持多个方法一起测试,步骤和上面一样,写在同一个测试类中,如:

	class ArrayAdd
	{
		[TestCase( "5638", Result = new int[] { 8, 3, 6, 5 ,0} )]
		[TestCase( "0456", Result = new int[] { 6, 5, 4, 0 ,0} )]
		public int[] testGetUserInput( string szInput )
		{
			return Program.GetUserInput( szInput );
		}
		//[TestCase( new int[] { 1, 1, 2, 3 }, new int[] { 1, 1, 0, 8 }, Result = new int[] { 2, 2, 2, 1, 1 } )]
		[TestCase( new int[] { 1, 2, 3 }, new int[] { 1, 0, 0 }, Result = new int[] { 2, 2, 3 ,0,0} )]
		[TestCase( new int[] { 1, 2, 3 }, new int[] { 1, 0, 8 }, Result = new int[] { 2, 2, 1 ,1,0} )]
		
		public int[] testAdd( int[] nArray1, int[] nArray2 )
		{
			return Program.Add( nArray1, nArray2 );
		}
	}

11、实际测试时,主要对函数的边界值进行测试,边界值若没有问题,一般其他值也都没有问题。

二、错误排除
当显示红色时,表示有错误,有可能是函数(方法)错误,有可能是给值错误。

1、可以通过错误提示,判断错误问题
例如可能提示:预期值为“4” 实际值为“1”数组索引超出string无法隐式转换为int等等,需要通过具体的来判断。

2、没有错误提示,直接是Failed、InValid,此时考虑前面步骤是否都正确,检查格式

你可能感兴趣的:(Syntec,C#培训)