2011年8月12日 星期五

[C#] NUnit

NUnit 2.0 is an excellent example of idiomatic design. Most folks who port xUnit just transliterate the Smalltalk or Java version. That's what we did with NUnit at first, too. This new version is NUnit as it would have been done had it been done in C# to begin with. (Kent Beck)

Getting Started with NUnit
  1. Download Current Production Release. (NUnit 2.5.10 is the current production release.)
  2. Suppose we are writing an adder class – Adder. The Adder class may look like this:
    namespace Adder
    {
    public class Adder
    {
    public int Add(int x, int y) { return x - y; }
    }
    }
  3. Now let’s write a test for this class – AdderTest.
    using NUnit.Framework;
    
    namespace Adder.Test
    {
    [TestFixture]
    public class AdderTestUnderNUnit
    {
    [Test]
    public void OneAddsOne() 
    {
    Adder adder = new Adder();
    Assert.AreEqual(2, adder.Add(1, 1));
    }
    }
    }
  4. Add nunit.framework DLL references.
  5. Compile to DLL.
  6. Open this DLL in the gui runner and run it. Failed:
    Adder.Test.AdderTestUnderNUnit.OneAddsOne:
    Expected: 2
    But was: 0
    Fix the error. Compile and run it again. Passed.

NUnit is a unit-testing framework for all .Net languages. It is written entirely in C# and has been completely redesigned to take advantage of many .NET language features, for example custom attributes and other reflection related capabilities.

沒有留言:

張貼留言