Translate

Thursday, 23 July 2009

ExpectedException - NotImplementedException

Recently, i got to thinking about how well suited the NotImplementedException is for Test-First approach of software development.

In Test-First or Test-Driven approach, you are required to write your tests first before writing any line of code.

For example, if you were to provide for a Calculator class, it is required that you write tests for the class first. But then, how do you write tests for a class whose operations do not exist? Simple. You test for the NotImplemented Exception!

There are many techniques available in NUnit. For instance, the Assert.Throws and .DoesNotThrow are good ways of asserting for an exception or you can simply use the [ExpectedException] attribute and decorate the test method so that the test knows that if NotImplementedException is thrown that is the right behavior of the test!

Below is a simple Hello World example demonstrating the usage of ExpectedException attribute alongwith the usage of the TestDelegate type in NUnit and writing to the Console (TextOutput pane) of the NUnit GUI.

using NUnit.Framework;
using System.Diagnostics;
using System;
namespace NUnit251_Tests
{
[TestFixture]
public class Class1
{
private WriteToNUnitConsole traceListener;
private SayHelloClass obj;
public class WriteToNUnitConsole:TraceListener
{
public override void Write(string message)
{
//throw new NotImplementedException();
Console.Write(message + "from NUnit");
}
public override void WriteLine(string message)
{
throw new NotImplementedException();
}
}
[SetUp]
public void InitTestData()
{
if (!Trace.Listeners.Contains(traceListener)){
traceListener=new WriteToNUnitConsole();
Trace.Listeners.Add(traceListener);
}
}
[TearDown]
public void DestroyTestData()
{
Trace.Listeners.Remove(traceListener);
}
[Test]
public void TestSayHelloWithWrite()
{
obj = new SayHelloClass();
Assert.DoesNotThrow(() => Trace.Write(obj.SayHello()));
}
[Test]
[ExpectedException("System.NotImplementedException")]
public void TestSayHelloWithWriteLine()
{
obj = new SayHelloClass();
obj.SayHelloThrowsException();
// Assert.Throws(typeof(NotImplementedException), (() => obj.SayHelloThrowsException()));
}

}
}

using System.Diagnostics;
namespace NUnit251_Tests
{
public class SayHelloClass
{
public string SayHello()
{
return "Hello World!";
}
public void SayHelloThrowsException()
{
//Trace.WriteLine("This method is not implemented");
throw new System.NotImplementedException();
}
}
}

As usual, i have commented out lines for you to try out different combinations.

This code has two tests - one commented and the other live. When both are uncommented, one test will pass and the other fail.

Happy TDD!

No comments: