NUnit属性TestCaseSource学习笔记

有这么一个计算数组最大值的方法.

 

namespace NUnitTest
{
    
public class MathCompute
    {
        
public int Largest(int[] array)
        {
            
if (null == array || 0 == array.Length)
            {
                
throw new Exception("参数传递错误");
            }

            
int largest = Int32.MinValue;

            
foreach (int element in array)
            {
                
if (element > largest)
                {
                    largest 
= element;
                }
            }

            
return largest;
        }
    }
}


我们写一段测试代码,使用NUnit的TestCaseSource属性测试它.


namespace NUnitTest
{
    [TestFixture]
    
public class MathComputeTest
    {
        
private MathCompute mc;

        [TestFixtureSetUp]
        
public void Init()
        {
            mc 
= new MathCompute();
        }

        [Test, TestCaseSource(
"LargestCases")]
        
public void TestLargest(int[] arr,int expected)
        {
            Assert.AreEqual(expected,mc.Largest(arr));
        }
        
        
#region 数据部分
        
static object[] LargestCases =
        { 
            
new object[] {new int[]{1,2,3,4},4},
            
new object[] {new int[]{-2-3-5-9},-2},
            
new object[] {new int[]{1},1},
            
new object[] {new int[]{20,20,20,20},20},
            
//new object[] {new int[]{},null}
        };
        
#endregion
    }
}


上面的代码提供了4组数据当做测试用例.

 运行一下:测试成功通过,如下图.

 

下面使用TestCaseSource的另一个构造函数

TestCaseSourceAttribute(Type sourceType, string sourceName);


 写如下测试代码

 

[Test, TestCaseSource(typeof(Class1), "LargestTestCases")]
public int TestLargest(int[] arr)
{
    
return mc.Largest(arr);
}


 数据源类

class Class1
    {
        
static IEnumerable<TestCaseData> LargestTestCases
        {
            
get
            {
                
yield return new TestCaseData(new int[] { 1234 }).Returns(4);
                
yield return new TestCaseData(new int[] { -2-3-5-9 }).Returns(-2);
                
yield return new TestCaseData(new int[] { 120-1-2 }).Returns(2);
                
yield return new TestCaseData(new int[] { 1 }).Returns(1);
                
yield return new TestCaseData(new int[] { 202020 }).Returns(20);
                
yield return new TestCaseData(new int[] { })
                     .Throws(
typeof(Exception))
                     .SetName(
"参数传递错误")
                     .SetDescription(
"参数错误");                  
            }
        }
    }


 运行一下:测试结果如下

 


 

   显而易见,TestCaseSource不仅可以提供多个测试用例进行测试,同时也把测试代码和测试数据有效地分离,

,便于管理和更新测试数据。

   但是,也有一个问题。就是每次修改数据后都要进行编译才能更新数据。效率不高。

 


 

Question:能否把数据存放在XML文件里,定义好数据的Type和Value,让程序动态加载、初始化数据,然后传给测试程序。

      这样我就可以直接改XML里的数据,而不用管代码如何如何了。

 

希望各位路过的博客园大大们给小弟指点一下。

 


 

 参考资料:NUnit Documentation

 

 

posted on 2009-12-03 20:21  nizhuguo  阅读(705)  评论(0编辑  收藏  举报

导航