编写测试案例(Test Cases)必须定义Test Fixture,在NUnitLite里使用属性[TestFixture]标识该类为Test Fixture。具体的测试就是该类的方法(Methods)。NUnitLite支持SetUp和TearDown,SetUp在执行测试案例之前先执行,用于初始化和分配资源,可以通过属性[SetUp]指定SetUp方法;TearDown在执行完测试案例后执行,用于释放相应的资源,可以使用属性[TearDown]指定TearDown方法。属性[Test]用于定义需要执行的测试案例,Test Runner会执行Test Fixture下所有的[Test]方法。
下面为测试案例的编写,也就是[Test]方法。
[Test] public void ExecuteNonQueryTest() { int i = sqlCe.ExecuteNonQuery("delete from t"); Assert.That(i, Is.GreaterThan(-1));
i = sqlCe.ExecuteNonQuery("insert into t (f1, f2) values (1, 'abc')"); Assert.That(i, Is.GreaterThan(-1));
i = sqlCe.ExecuteNonQuery("update t set f2 = 'xyz' where f1 = 1"); Assert.That(i, Is.GreaterThan(-1)); }
[Test] public void ExecuteReaderTest() { SqlCeDataReader reader = sqlCe.ExecuteReader("select * from t"); Assert.NotNull(reader); Assert.True(!reader.IsClosed); while (reader.Read()) { Assert.That(Is.Equals(reader["f2"], "abc")); } reader.Close(); }
[Test] public void ExecuteDataSetTest() { DataSet ds = sqlCe.ExecuteDataSet("select * from t"); foreach (DataRow dr in ds.Tables[0].Rows) { Assert.That(dr["f2"], Is.EqualTo("xyz")); } }
[Test] [ExpectedException(typeof(ApplicationException))] public void ThrowsException() { throw new ApplicationException("an application exception"); } |
在 NUnitLite中进行检验值还是使用Assert,但是不能使用NUnit下的AreEquels等判断方法,需要使用Assert.That和Is 类组合完成AreEquels等判断函数的功能。同时NUnitLite还是支持异常的捕捉(ExpectedException)。
程序运行后会生成运行结果如下:
NUnitLite version 0.2.0 Copyright 2007, Charlie Poole
Runtime Environment - OS Version: Microsoft Windows CE 5.0.0 .NET Version: 2.0.7045.0
4 Tests : 0 Errors, 1 Failures, 0 Not Run
Errors and Failures:
1) ExecuteReaderTest (TestNameSpace.SqlCeHelperTest.ExecuteReaderTest) Expected: True But was: False
at TestNameSpace.SqlCeHelperTest.ExecuteReaderTest() at System.Reflection.RuntimeMethodInfo.InternalInvoke() at System.Reflection.RuntimeMethodInfo.InternalInvoke() at System.Reflection.RuntimeMethodInfo.Invoke() at System.Reflection.MethodBase.Invoke() at NUnitLite.Reflect.InvokeMethod() at NUnitLite.TestCase.InvokeMethod() at NUnitLite.TestCase.RunTest() at NUnitLite.TestCase.RunBare() at NUnitLite.TestCase.Run() at NUnitLite.TestCase.Run() at NUnitLite.TestSuite.Run() at NUnitLite.TestSuite.Run() at NUnitLite.Runner.TestRunner.Run() at NUnitLite.Runner.TestRunner.Run() at NUnitLite.Runner.TextUI.Run() at NUnitLite.Runner.TextUI.Execute() at TestNameSpace.TestForm.Main() |