VS2010单元测试的使用【1】

  由于本人学习C#是从代码直接看起的,在之前都是接触的Java的相关开发工具,所以到使用VS的时候,仅仅是在用了代码的编辑、编译、运行、调试等主要功能,很多VS自带的小功能都不是很熟悉,最近在一个旧的项目里看到有加入UnitTest的,所以想自己了解一下UnitTest的使用。

  下面继续开始记录:

  1.在使用时创建了一个简单的加减乘除的ConsoleApp,包括Add、Dec、Div、Mul四个方法,传入两个double类型的数,返回运算后的double值。

  2.右击某个方法(Add/Dec/Div/Mul),选择Create Unit Test

  

   接下来就可以看到下面的界面,选择需要增加Test方法的方法:

    选择指定的方法后,点OK,命名测试项目的名称

    Create后即可看到成功生成的UnitTest项目了~~~

  看一下Reference,这里引用了Microsoft.VisualStudio.QualityTools.UnitTestFramework以及需要测试的项目的程序集MyNumberOperation。

  Microsoft.VisualStudio.TestTools.UnitTesting 命名空间提供支持单元测试的类

  【msdn:http://msdn.microsoft.com/zh-cn/library/ms244252(v=VS.100).aspx

  看一下我们生成的测试方法:

View Code
namespace MyUnitTest
{


///<summary>
///This is a test class for NumberOperationTest and is intended
///to contain all NumberOperationTest Unit Tests
///</summary>
[TestClass()]
public class NumberOperationTest
{


private TestContext testContextInstance;

///<summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}

#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion


///<summary>
///A test for Add
///</summary>
[TestMethod()]
public void AddTest()
{
double a = 0F; // TODO: Initialize to an appropriate value
double b = 0F; // TODO: Initialize to an appropriate value
double expected = 0F; // TODO: Initialize to an appropriate value
double actual;
actual = NumberOperation.Add(a, b);
Assert.AreEqual(expected, actual);
Assert.Inconclusive("Verify the correctness of this test method.");
}
}
}

  针对我们在创建UnitTest时只选择了Add方法,所以这里只会有一个AddTest方法,如果之前选择了Add以及其他几个方,那这里也会对应生成Test方法。

  AddTest方法里,设定了a、b、expected几个值,分别解释一下几个值的用处:

  a,b:Add方法的两个参数,可以在运行测试之前手动编辑这两个值,以测试不同情况;

  expected:设定a,b后,期望通过调用Add方法后的返回值,下面将用expected与返回值做比较

 

  Assert.AreEqual(expected, actual);

  这里通过断言的方式检查返回值是否和预期的值相等,相等返回TRUE,不等返回FALSE!

  最后一句Assert.Inconclusive是用来显示测试成功通过的显示。

  有关Assert的使用:

  【msdn:http://msdn.microsoft.com/zh-cn/library/microsoft.visualstudio.testtools.unittesting.assert_methods.aspx

  试一试调试情况:

 

 

  当然如果expected设值为其他值,比如12,在Assert.Actual的是很,断言就会报错:

 

 

   这个就记录到这里,只是简单的使用UnitTest,后面还要再总结一下数据驱动的UnitTest。

posted @ 2011-10-24 10:38  liver.wang  阅读(1125)  评论(0编辑  收藏  举报