Appendix II. Building Your Own Simple Test Framework with Excel
One of the issues with NUnit is it is focused specifically on testing .NET solutions. In the real world, you might have Visual Basic, C++ solutions as well as .NET C# and VB.NET code. I like to have one place where I can run all the tests for the entire system. Using Excel is fairly generic, and most languages can expose a COM interface for Excel to work with. In the following exercise, we will build a simple framework with C# and VBA in Excel.In this exercise, we build a test framework for a .NET class library using Excel as the main engine and tests that are exposed in the form of a COM interface. So let's get into it:
1. Create a new C# class library called ExcelTestLibrary.2. In the Class1.cs file, create a class that supports a COM interface so that we can call it from Excel. We can use the ClassInterface attribute, as shown:
3. In Solution Explorer, right-click the project and select Properties to bring up the Property Pages dialog box. In the Configuration Properties / Build section, set the Register for COM Interop Output to True, as shown in Figure A-1. This will generate a type library and register it in the system Registry.
using System;
using System.Runtime.InteropServices;
namespace ExcelTestLibrary
{
[ClassInterface(ClassInterfaceType.AutoDual)]
public class Tests
{
public int TestCount
{
get
{
return 2;
}
}
public string[] RunTests()
{
string[]results = new string[2];
results[0] = Test1();
results[1] = Test2();
return results;
}
private string Test1()
{
return "Success: Test1 Ran";
}
private string Test2()
{
return "Failure: Test2 Ran";
}
}
}
Figure A-1. Register for COM Interop.
[View full size image]

6. Run the macro and have a look at the spreadsheet. You should see the results highlighted in Figure A-2.
Sub RunTests()
Dim testLib As New ExcelTestLibrary.Tests
Dim results() As String
results = testLib.RunTests()
Dim nTest As Integer
Dim result As String
Dim resultRow As Range
For nTest = 0 To testLib.TestCount - 1
result = results(nTest)
Set resultRow = Range(Sheet1.Cells(nTest + 1, 1),
Sheet1.Cells(nTest + 1, 10))
If Left(result, 7) = "Success" Then
resultRow.Interior.Color = RGB(0, 255, 0)
Else
resultRow.Interior.Color = RGB(255, 0, 0)
End If
Sheet1.Cells(nTest + 1, 1) = result
Next
End Sub
Figure A-2. Results of Our Tests in Excel.
[View full size image]

- Save the sheet after the tests have run into an archive so that you can track the progress of tests through the project life cycle. Format the sheet with headings so that it is presentable to management as an output of the build and test process. Create a mechanism to return the success or failure output as a Boolean separately from a results string. Think of how you can incorporate this into your solution at work.
