# Friday, August 06, 2004

The new TestFu.Gestures framework contains a set of classes to simulate user interaction, called "gestures". (Currently only the mouse is implemented) 

Why gestures ?

Lately, I've tackling the Windows.Forms problem. At first, I decided to use Reflection to get the On*** methods and use them to raise the events. This method worked for simple events such as Click but was showing some serious problem when you wanted to hit events like MouseEnter and MouseLeave. Obviously the Reflection solution was not good.

Let's think again about Form testing: we are mainly testing events that are triggered by user interaction (mouse or keyboard) so in order to test this, we should "mock" the user. The Form sees the user as a sequence of mouse or keyboard gestures, therefore, we need tools to generate artificial click, mouse moves, etc...

Gesture definition

A gesture can be any user input: mouse click, mouse move, key pressed, etc. A gesture can also be a combination of other gesture. For example, drag and drop is the sequence of mouse down, move, mouse up.

Generating mouse events

At first, I tried to simulate the mouse using the .Net class Cursor, but it was also showing limitation... so it seemed like this was a work for native methods and Interop. 

A quick googling over the subject showed that two methods from user32.dll where exactly designed for that: mouse_event and keybd_event. (I'll drop aside keybd_event for the moment). I found the correct C# signature and some example in the excellent www.pinkove.net site.

This method is harnessed in the state helper class VirtualInput which has several helper methods to simulate user interactions:

// simulate a left click
VirtualInput.MouseClick();
// move the mouse
VirtualInput.MouseMove(10,10);
// push right button down
VirtualInput.MouseDown(MouseButtons.Right);

Gestures interfaces

Now, that we have a method to generate mouse events, we can start to define the TestFu.Gesture framework. A gesture is defined by a simple interface:

public interface IGesture
{   
    Form Form{get;}
    void Start();
}

That's pretty minimalistic. The Start method executes the gesture and the Form represents the tested System.Windows.Form instance (we need it to convert coordinates between client and screen).

It is important to note that gestures should not be executed in the main thread, otherwize you will not simulate "correctly" the user interaction. Therefore, the signature of the Start method is intended to be easily "Theard startable".

A mouse gesture is defined by the IMouseGesture that specializes IGesture:

public interface IMouseGesture : IGesture
{
    MouseButtons Buttons {get;}
}

The Buttons property value gives the combination of mouse buttons involved in the gesture.

A simple gesture: the mouse click

To illustrate these interfaces, we show the mouse click gesture is implemented. This gesture inherits from an abstract base class MouseGestureBase, which implements IMouseGesture:

public class ClickMouseGesture : MouseGestureBase
{
   ... // constructors

   public override void Start()
   {
      VirtualInput.MouseClick(this.Buttons);
   }
}

In fact, this example shows well that gestures implement the Metod Invocation Object pattern (if I recall well).

A gesture factory

In order  to simplify things, TestFu.Gestures come with a factory for gestures object, GestureFactory. This factory contains a bunch of helper classes to save you time and keystrokes. In the following example, we use the factory to create a "click" gesture and execute it in a separate thread:

Form form =...; // target form
GestureFactory factory = new GestureFactory(form);

IGesture clik = factory.MouseClick();
GestureFactory.Start(click);

Gesture library

This section gives the list of available gestures with example. For the example, we suppose that we have a form that contains two controls (left and right) and a factory:

Form form = ...;
Control left = Form.LeftControl;
Control right = Form.RightControl;
GestureFactory factory = new GestureFactory(form);
  • Mouse click
    // click
    IGesture g = factory.MouseClick();
    // click control
    g = factory.MouseClick(left);
    // click location
    g = factory.MouseClick(new Point(10,20));
    
  • Mouse move
    // move to location
    g = factory.MouseMove(new Point(...,...));
    // move to the center of a control
    g = factory.MouseMove(left); 
    
  • Drag and drop between different locations
    // drag and drop between two controls
    g = DragAndDrop(left,right);
    
  • Sleep
    // sleep 1 sec
    g = factory.Sleep(1000);
  • Sequence of gestures
    // click left and then right
    g = factory.Sequence(
        factory.MouseClick(left),
        factory.MouseClick(right)
        );
  • Repeat a gesture
    // click left 3 times
    g = factory.Repeat(
        factory.MouseClick(left),
        3);
    
posted on Friday, August 06, 2004 8:43:00 AM (Pacific Daylight Time, UTC-07:00)  #    Comments [11]
# Tuesday, August 03, 2004

This blog presents the filtering tools that QuickGraph contains. Filters enables you to create a filtered view of a vertex collection, edge collection, a vertex list graph or other more advanced graphs.

The basics:

All the filters relay on two interfaces: IVertexPredicate and IEdgePredicate. Both those interface have a Test method that takes a IVertex (resp. IEdge) as argument and returns true if the instance should be kept, or false if it should be filtered out. Special collection, in the System.Collections.Filtered namespace, can be used to create a filtered enumeration of vertices and edges.

Examples

Let's take the file dependency example, as introducted in Fun with Graphs (2): Drawing graphs with QuickGraph and NGraphviz

This graph is part of the QuickGraphTest demo project:

BidirectionalGraph graph = GraphProvider.FileDependency();

Filtering Vertices

The BidirectionalGraph class supports methods Select** that take a predicate as argument. We can use it to filter the vertices and display the source vertex only (a source has no in-edge):

Console.WriteLine("Source vertices:");
foreach(NamedVertex v in graph.SelectVertices(Preds.SourceVertex(graph)))
{
    Console.WriteLine("\t{0}",v.Name);
}

[Output]
Source vertices:
        zow.h
        boz.h
        dax.h

Preds is an static helper class. Preds.SourceVertex returns a SourceVertexPreicate instance implemented as follows:

using System;
namespace QuickGraph.Predicates
{
    using QuickGraph.Concepts;
    using QuickGraph.Concepts.Predicates;
    using QuickGraph.Concepts.Traversals;

    public class SourceVertexPredicate : IVertexPredicate
    {
        private IBidirectionalGraph graph;
        public SourceVertexPredicate(IBidirectionalGraph graph)
        {
            if (graph==null)
                throw new ArgumentNullException("graph");
            this.graph = graph;
        }

        bool IVertexPredicate.Test(IVertex v)
        {
            return this.graph.InEdgesEmpty(v);
        }
    }
}

In the case your graph does not implement Select methods, you can directly use filtered enumerable collection such as the FilteredVertexEnumerable. Here we will show the sinks of the graph:

Console.WriteLine("Sink vertices:");
FilteredVertexEnumerable filteredVertices =
    new FilteredVertexEnumerable(
        graph.Vertices,
        Preds.SinkVertex(graph)
    );
foreach (NamedVertex v in filteredVertices)
{
    Console.WriteLine("\t{0}",v.Name);
}

[Output]
Sink vertices:
        killerapp

Filtering edges

Edges can be filtered similarly to vertices using IEdgePredicate instances. The EdgePredicate class can be used to combine a IEdgePredicate and 2 IVertexPredicate for the source and the target of the edge.

Filtering entire graph

One can also creating filtered views of entire graphs. Let's consider another graph for this example: the finite state machine of a calculator:

 

In this case, we would like to filter out the S4 state and all the edges attached to this sate. One possible solution is to create a dictionary of vertices colors (VertexColorDictionary) where all the vertices are white, except S4 which is set to black.

// create and fill the dictionary
VertexColorDictionary vertexColors = new VertexColorDictionary();
IVertexPredicate pred = new NameEqualPredicate("S4");
foreach (IVertex v in graph.Vertices)
{
    if (pred.Test(v))
        vertexColors[v] = GraphColor.Black;
    else
        vertexColors[v] = GraphColor.White;
}

Then we can create the filters to ignore black vertices:

// create filters for the main graph
// no back vertex
IVertexPredicate vp = new NoBlackVertexPredicate(vertexColors);

// all edge that do not start or end on a blackvertex
IEdgePredicate ep = new EdgePredicate(
    Preds.KeepAllEdges(),
    vp
   );

At last, we use FilteredVertexAndEdgeListGraph to create a filtered IVertexListGraph

IVertexAndEdgeListGraph filteredGraph = new FilteredVertexAndEdgeListGraph(graph,ep,vp);

The image belows shows the result of the filtering. The S4 state and all its adjacent edges are gone.

posted on Tuesday, August 03, 2004 9:37:00 AM (Pacific Daylight Time, UTC-07:00)  #    Comments [0]

The release 2.20 of MbUnit (bundled with TestFu and QuickGraph) has been released. See latest release page on this blog for the download links.This release was compiled against .Net v1.1. Note that MbUnit is now developped using Visual C# 2005 Express and compile using MSBuild (thanks to the expert help of Jamie Cansdale).

New features:

Breaking changes:

  •  The factories for the TypeFixture must tag the factory property with FactoryAttribute attribute

Bugs fixed:

  • Console appplication fixed,
  • Nant task fixed,
  • Assertion messages fixed,
  • NUnit fixture support fixed,
  • SqlAdministrator bugs fixed,
  • SqlGenerator fixed,
  • Random data generation of DataSet fixed 

 

posted on Tuesday, August 03, 2004 8:28:00 AM (Pacific Daylight Time, UTC-07:00)  #    Comments [3]

In a previous post, I introduced DataGraph, a graph of the tables and relations available in TestFu. In this post, I present DataJoinGraph, the graph of a table join in a query:

  • Vertx: the DataTable and alias. Since a table can be referenced by multiple alias, the alias is used as the unique identifier of the vertex. Ex: User, "U"
  • Edge: the DataRelation and the type of join (Inner, Outer, etc...)

For the simple join situation (when two tables are simply linked), the DataJoinGraph uses the DataGraph of the database to resolve which DataRelation to use. (In the future, one could think about finding the minimum weight path and creating the join). For the moment, the DataJoinGraph can be used to create an ordering of joins, compatible with T-SQL. Let see this with some example

Creating the graph

DataJoinGraph lives in TestFu.Graph and takes a DataGraph as argument:

DataSet ds = ...;
DataJointGraph joinGraph = new DataJoinGraph(DataGraph.CreateGraph(ds));

Populating the graph

At first, you add the tables involved in the join with their alias (Note that aliases must be unique):

DataTableJoinVertex users = joinGraph.AddVertex(ds.Tables["Users"],"U");
DataTableJoinVertex orders = joinGraph.AddVertex(ds.Tables["Orders"],"O");

Afterwards, you add the different joins between the tables:

joinGraph.AddEdge(users,orders);

Since there is only one DataRelation linking users and orders, the DataJoinGraph can find the DataRelation to use. Moreover, by default we have use a Inner join but this can be modified by providing the proper parameter:

joinGraph.AddEdge(users,orders,JoinType.Outer);

This procedure is continued for the joins of the query.

Create an ordering

The DataTableJoinSortAlgorithm can be used to order the joins to create a SQL query:

DataTableJoinSortAlgorithm algo = new DataTableJoinSortAlgorithm(joinGraph);
algo.Compute();

The StartVertex property returns the first DataTableJoinVertex of the join, and the Joins property returns an ordered collection of DataRelationJoinEdge. For instance, the following method can be used to display the joins in SQL:

protected void ShowJoins()
{
    DataTableJoinVertex v = this.algo.StartVertex;
    Console.WriteLine("{0} AS {1}",v.Table.TableName, v.Alias);

    foreach (DataRelationJoinEdge edge in algo.Joins)
    {
        DataTableJoinVertex next = null;
        if (edge.Source==v)
            next = (DataTableJoinVertex)edge.Target;
        else
            next = (DataTableJoinVertex)edge.Source;
        Console.WriteLine("{0} JOIN {1} AS {2} ON ",
            edge.JoinType.ToString().ToUpper(),
            next.Table.TableName,
            next.Alias
            );

        bool needAnd=false;
        for (int i = 0; i < edge.Relation.ParentColumns.Length; ++i)
        {
            if (needAnd)
                Console.Write(" AND");
            else
                needAnd=true;
            Console.Write(" {0}.{1} = {2}.{3}",
                edge.Source.Alias,
                edge.Relation.ParentColumns[i].ColumnName,
                edge.Target.Alias,
                edge.Relation.ChildColumns[i].ColumnName
                );
        }
        Console.WriteLine();
        v = next;
    }
}

Some examples

Here are a few examples of use and their corresponding output using the ShowJoins method.

  • [C#]
    this.graph.AddVertex(this.dataSource.Users, "U");
    [Output]
    Users AS U
  • [C#]
    DataTableJoinVertex users = this.graph.AddVertex(this.dataSource.Users, "U");
    DataTableJoinVertex orders = this.graph.AddVertex(this.dataSource.Orders, "O");
    DataRelationJoinEdge uo = this.graph.AddEdge(users, orders, JoinType.Inner);
    [Output]
    Users AS U
    INNER JOIN Orders AS O ON 
     U.UserID = O.UserID
  • [C#]
    DataTableJoinVertex users = this.graph.AddVertex(this.dataSource.Users, "U");
    DataTableJoinVertex orders = this.graph.AddVertex(this.dataSource.Orders, "O");
    DataTableJoinVertex products = this.graph.AddVertex(this.dataSource.Products, "P");
    DataTableJoinVertex orderProducts = this.graph.AddVertex(this.dataSource.OrderProducts, "OP");
    DataRelationJoinEdge pop = this.graph.AddEdge(products, orderProducts, JoinType.Inner);
    DataRelationJoinEdge uo = this.graph.AddEdge(users, orders, JoinType.Inner);
    DataRelationJoinEdge oop = this.graph.AddEdge(orders, orderProducts, JoinType.Inner);
    
    [Output]
    Orders AS O
    INNER JOIN OrderProducts AS OP ON 
     O.OrderID = OP.OrderID
    INNER JOIN Products AS P ON 
     P.ProductID = OP.ProductID
    INNER JOIN Users AS U ON 
     U.UserID = O.UserID
    
posted on Tuesday, August 03, 2004 7:45:00 AM (Pacific Daylight Time, UTC-07:00)  #    Comments [0]
# Friday, July 30, 2004

As MSBuild is getting more and more attention from the community, it was time for MbUnit to propose a MSBuild Task to execute the tests. This is now done (in the CVS) and the task will be available in the next release.

MSBuild Task Creation Process

I have used the MSDN articles on MSBuild as a good source of information for building the MbUnit task (see part 1 and part 2) from Christophe NasarreChristophe Nasarre. More specifically, the part 2 of the articles gives a detailled how-to on the custom task creation. I won't repeat the article here.

First impression: MSBuild way of defining custom properties is rather limited. I would have though that they could have used Xml serialization so that any serializable object could be used in the task definition. That's sad...

Ok, we start by creating a new project, added Microsoft.Build.Framework.dll and Microsoft.Build.Utilities.dll references and we add the MbUnit class.

using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using MbUnit....; // MbUnit usings

namespace MbUnit.MSBuild.Tasks
{
    public class MbUnit : Task
    {
        public override bool Execute()
        {
            ...
        }
    }
}

As you can see, the MbUnit class derives from Task, which implements ITask. The Execute method is invoked by MSBuild. Next step is to add some parameters to the task in order to setup the test execution. There are a bunch of them, I will focus on the test assembly paths:

public class MbUnit : Task
{
    private string[] assemblies;
    
    [Required]
    public string[] Assemblies
    {
        get { return this.assemblies; }
        set { this.assemblies = value; }
    }

Note the Required attribute which is used to mark required properties. We can now implement the main loop: the Execute method. The execute method outline is rather simple:

  • create an empty test report,
  • for each test assembly file path,
    • load the assembly in a separate AppDomain,
    • run tests,
    • merge results in the report
  • output the report to the desired formats
public override bool Execute()
{
    this.result = new ReportResult();
    try
    {
        foreach (string testFilePath in this.Assemblies)
        {
            string path = GetFilePath(testFilePath);
            if (path==null)
                return false;
            using (TestDomain domain = new TestDomain(path))
            {
                domain.ShadowCopyFiles = false;
                domain.Load();
                domain.TestTree.RunPipes();
                result.Merge(domain.TestTree.Report.Result);
            }
        }
        this.GenerateReports();
    }
    catch (Exception ex)
    {
        this.Log.LogError("Unexpected failure during MbUnit execution");
        return false;
    }
    return true;
}

It is time to prepare the project to debugging the task. As advised in the article, set the output path of the project to the .Net 2.0 folder and use MSBuild.exe as starting program. Put in the command line arguments the name of the XML file containing the MbUnit project.

Sample Project

This is a sample MSBuild project that executes MbUnit tests:


<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <UsingTask AssemblyName="MbUnit.MSBuild.Tasks" TaskName="MbUnit.MSBuild.Tasks.MbUnit"/>

    <ItemGroup>
        <TestAssemblies Include="..\MbUnit.Demo\bin\Debug\MbUnit.Demo.exe" />
    </ItemGroup>

    <Target Name="Tests"> 
        <MbUnit
            Assemblies ="@(TestAssemblies)"
            HaltOnFailure="false"
            ReportTypes="Xml;Text;Html;Dox"
        /> 
    </Target>
</
Project>

The output of this task is as follows:

Microsoft (R) Build Engine Version 2.0.40607.16
[Microsoft .NET Framework, Version 2.0.40607.16]
Copyright (C) Microsoft Corporation 2004. All rights reserved.
Target "Tests" in project "ProjectSample.xml"
   Task "MbUnit"
      Loading C:\Documents and Settings\dehalleux\My Documents\Projects\mbunit\src\MbUnit.Demo\bin\Debug\MbUnit.Demo.exe
      Found  3 tests
      Running fixtures.
      Tests finished: 3 tests, 1 success, 2 failures, 0 ignored
      Unloading AppDomain
      All Tests finished: 3 tests, 1 success, 2 failures, 0 ignored in 1,56469663043767 seconds
      Generated Xml report at MbUnit.15_26_26.15_26_26.xml
      Generated Text report at MbUnit.15_26_26.15_26_26.txt
      Generated Html report at MbUnit.15_26_26.15_26_26.html
      Generated Dox report at MbUnit.15_26_26.15_26_26.dox.txt
I'll have a couple beers to this tonight :)
posted on Friday, July 30, 2004 12:57:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [6]
# Thursday, July 29, 2004

I have sent the manuscript of my PhD to the jury today. The thesis speaks about stability and control of quasilinear hyperbolic partial differential equations (for example, stabilization of open channels). I won't speak about it in details here but I can give you the title:

Boundary Stabilization Techniques of Quasi-Linear Hyperbolic Initial-Boundary Value Problem.

Of course, the relation to software testing is not obvious... because there is none.

posted on Thursday, July 29, 2004 1:19:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [2]
# Wednesday, July 28, 2004

The next version of MbUnit (2.20) will have a new custom attribute that will let you assert on the values of PerformanceCounters: PerfCounterAttribute. (Idea suggested by ISerializable). This means that you can make an assertion an every perfomance counter on your machine!

Here's a sample fixture that shows how the attribute can be used:

using System;
using MbUnit.Core.Framework;
using MbUnit.Framework;
namespace MbUnit.Demo
{
  [TestFixture]
  public class PerfCounterDemo
  {
    [Test]
    [PerfCounter(".NET CLR Memory", "% Time in GC", 10)]
    public void AllocateALotOfObjects()
    {
      ...
    }

    [Test]
    [PerfCounter(".NET CLR Loading", "% Time Loading", 10)]
    [PerfCounter(".NET CLR Security", "% Time in RT checks", 10000)]
    [PerfCounter(".NET CLR Security", "% Time Sig. Authenticating", 10)]
    [PerfCounter(".NET CLR Memory", "# Bytes in all Heaps", 5000000, Relative =true)]
    [PerfCounter(".NET CLR Jit", "% Time in Jit", 10)]
    public void MonitorMultipleCounters()
    {
      ...
    }
  }
}

Note that if you are too lazy to remember the names of the counters, I have written a CodeSmith template that creates a class filled with static helper methods for retreiving the counters. For example, the following class lets you write things like PerfCounterInfo.NetClrExceptions.NbofExcepsThrown.NextValue() using intellisense and without typing errors :)

using System;
using System.Diagnostics;
namespace MbUnit.Core.Framework
{
 public class PerfCounterInfo
 {  
  public sealed class NetClrExceptions
  {
   const string categoryName = @".NET CLR Exceptions";

   public sealed class NbofExcepsThrown
   {
    const string counterName = @"# of Exceps Thrown";

    public static float NextValue()
    {
     return NextValue(Process.GetCurrentProcess().ProcessName);
    }    
   }
   ...
posted on Wednesday, July 28, 2004 3:29:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [8]

The next version of TestFu will feature a DataSet graph object (DataGraph class) , i.e. a bidirectional directed graph G(V,E) where

  • V is the set of vertices, one vertex per DataTable in the DataSet, (DataTableVertex class)
  • E is the set of edges, one edge per DataRelation in the DataSet (DataRelationEdge class). The source vertex of the edge is the ParentTable, while the target is the ChildTable.

Why do we need a graph ?

Once you have the graph structure of the database, you use all the algorithms contained in the QuickGraph.Algorithms project: shortest path, topological sort, etc... In fact, you can even use it to draw the graph using the NGraphviz. There are of course other very interresting applications of this structure. For example, you can use the graph to create a table creation order such that will not violate the constraints, or you estimate the complixity of a join, etc...

Let's see some examples..

Creating a graph and basic usage

DataGraph lives in the TestFu.Data.Graph namespace and is built from a DataSet instance:

using Test.Data.Graph;
...
DataSet ds = ...;
DataGraph graph = DataGraph.Create(ds);

Now that we have a graph, we can iterate over it's vertices and edges:

// iterating the vertices (DataTableVertex)
foreach(DataTableVertex v in graph.Vertices)
{
    DataTable table = v.Table;
    ...
}

// iterating the edges
foreach(DataRelationEdge e in graph.Edges)
{
   DataRelation relation = e.Relation;
   ...
}

Let's see what other things we could do with graph.

Drawing the table structure:

This is an obvious usage of the graph and can be done quite easily using the QuickGraph.Algorithms.Graphviz.GraphvizAlgorithm class:

GraphvizAlgorithm gv = new GraphvizAlgorithm(this.graph);
gv.FormatVertex+=new FormatVertexEventHandler(gv_FormatVertex);
gv.FormatEdge+=new FormatEdgeEventHandler(gv_FormatEdge);
System.Diagnostics.Process.Start(gv.Write(dataSource.DataSetName));

...

void gv_FormatVertex(object sender, FormatVertexEventArgs e)
{
    DataTableVertex v = (DataTableVertex)e.Vertex;
    e.VertexFormatter.Shape = NGraphviz.Helpers.GraphvizVertexShape.Box;
    e.VertexFormatter.Label = v.Table.TableName;
}
void gv_FormatEdge(object sender, FormatEdgeEventArgs e)
{
    DataRelationEdge edge = (DataRelationEdge)e.Edge;
    e.EdgeFormatter.Label.Value = edge.Relation.RelationName;
}

The result on a sample DataSet is displayed below:

DataTable ordering

Another interresting application is to create an ordering of the DataTable such that if you fill the tables using this ordering, you will not break any constraint. This solves the old problem "which table should I populate first?". For example, in the example above, the ordering result would be:

  1. Users,
  2. Orders,
  3. Categories,
  4. Products,
  5. OrderProducts

Since this feature has a major interrest in TestFu, it is built-in in the DataGraph class:

DataTable[] tables = graph.GetSortedTables();
In the background, graph uses the QuickGraph.Algorithms.SourceFirstTopologicalSortAlgorithm algorithm class which creates a topological ordering of the vertices of a graph by choosing the vertices with least in degree (very simple algo, home made):

// sort tables
SourceFirstTopologicalSortAlgorithm topo = new SourceFirstTopologicalSortAlgorithm(graph);
topo.Compute();

// output results
DataTable[] result = new DataTable[topo.SortedVertices.Count];
int i = 0;
foreach (DataTableVertex v in topo.SortedVertices)
{
    result[i++] = v.Table;
}
return result;

The SourceFirstTopologicalSortAlgorithm takes a IVertexAndEdgeListGraph instance which graph implements. As you can see, having a graph representation of your DataSet, compatible with QuickGraph opens a realm interresting applications of existing graph theory algorithms.

Next step: "Smart" Random Data generation

Once the table ordering is computed, you can safely generate "smart" random data and feed your DataSet...

posted on Wednesday, July 28, 2004 9:29:00 AM (Pacific Daylight Time, UTC-07:00)  #    Comments [6]
# Tuesday, July 27, 2004

While writing the test for the NUnit fixture loader, I started to have some twisted tests. So twisted, they are worth mentionned in the blog. For instance, the steps I take to test NUnit load are:

  1. Load a NUnit fixture from the Assembly resources (as source code),
  2. Compile it and output an assembly using CodeDom.Compiler namespace,
  3. Load the newly created assembly using MbUnit, look for the tests and execute,
  4. Verify that the tests have been found, are executed and behaved as expected.
  5. Execute all those steps in a fixture

Twisted...

 

using System;
using System.IO;
using System.Configuration;
using System.Reflection;
using MbUnit.Core.Remoting;
using MbUnit.Core.Framework;
using MbUnit.Framework;
using MbUnit.Framework.Utils;
using System.CodeDom.Compiler;
using MbUnit.Core.Reports;
using MbUnit.Core.Reports.Serialization;
namespace MbUnit.Tests.Core.FrameworkBridges
{
  [TestFixture]
  [CurrentFixture]
  public class NUnitBridgeTest
  {
    private SnippetCompiler compiler;
    private ReportCounter counter;
    private ReportResult result;

    [SetUp]
    public void SetUp()
    {
      this.compiler = new SnippetCompiler();
      string nunitFolder = ConfigurationSettings.AppSettings["NUnitFolder"];
      string nunitFrameworkDll = Path.Combine(nunitFolder,@"NUnit.Framework.dll");
      this.compiler.Parameters.ReferencedAssemblies.Add(nunitFrameworkDll);
      this.compiler.LoadFromResource(
         "MbUnit.Tests.Core.FrameworkBridges.NUnitFixture.cs",
         Assembly.GetExecutingAssembly()
        );
      string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
      this.compiler.Parameters.OutputAssembly =
          Path.Combine(path, "NUnitBridgeTest.dll");
    }

    [Test]
    public void TestCaseCount()
    {
      LoadAndRunFixture();
      Assert.AreEqual(4, counter.RunCount);
    }

    [Test]
    public void SuccessCount()
    {
      LoadAndRunFixture();
      Assert.AreEqual(2, counter.SuccessCount);
    }

    ...

    private void LoadAndRunFixture()
    {
      this.compiler.Parameters.GenerateInMemory = false;
      this.compiler.Compile();
      this.compiler.ShowErrors(Console.Out);
      Assert.IsFalse(this.compiler.Results.Errors.HasErrors);

      // load assembly using MbUnit
      using (TestDomain domain = new TestDomain(this.compiler.Parameters.OutputAssembly))
      {
        domain.ShadowCopyFiles = false;
        domain.Load();

        // running tests
        domain.TestTree.RunPipes();
        
        result = domain.TestTree.Report.Result;
        counter = domain.TestTree.GetTestCount();
      }
    }
  }
}

And the loaded fixture is as follows:

using System;
using System.IO;
using NUnit.Framework;
namespace MbUnit.Tests.Core.FrameworkBridges
{
  [TestFixture]
  public class NUnitFixture
  {
    [TestFixtureSetUp]
    public void TestFixtureSetUp()
    {
      Console.Out.Write("TestFixtureSetUp");
    }
    [SetUp]
    public void SetUp()
    {
      Console.Out.Write("SetUp");
    }
    [Test]
    public void Success()
    {
      Console.Out.Write("Success");
    }
    [Test]
    public void Failure()
    {
      Console.Out.Write("Failure");
      Assert.Fail();
    }
    [Test]
    [ExpectedException(typeof(ArgumentNullException))]
    public void ExpectedException()
    {
      Console.Out.Write("ExpectedException");
      throw new ArgumentNullException("boom");
    }
    [Test]
    [Ignore("Because I want")]
    public void Ignore()
    {
      Console.Out.Write("Ignore");
      throw new Exception("Ignored test");
    }
    [TearDown]
    public void TearDown()
    {
      Console.Out.Write("TearDown");
    }
    [TestFixtureTearDown]
    public void FixtureTearDown()
    {
      Console.Out.Write("FixtureTearDown");
    }
  }
}
posted on Tuesday, July 27, 2004 6:17:00 PM (Pacific Daylight Time, UTC-07:00)  #    Comments [2]
# Sunday, July 25, 2004
Download available at www.dotnetwiki.org download page.
posted on Sunday, July 25, 2004 9:24:00 AM (Pacific Daylight Time, UTC-07:00)  #    Comments [4]