Third Shelf

Getting Fit, Uncle Bob style!

Posted in .net, productivity by Sydney du Plooy on April 23, 2011

Fit: Framework for Integrated Test

Great software requires collaboration and communication. Fit is a tool for enhancing collaboration in software development. It’s an invaluable way to collaborate on complicated problems–and get them right– early in development.

Fit allows customers, testers, and programmers to learn what their software should do and what it does do. It automatically compares customers’ expectations to actual results. [Cunn 07]

Read an introduction to FitNesse.

Installing FitNesse

To start using FitNesse with .net, you’ll need to download FitNesse and fitSharp. Once downloaded, place the fitnesse.jar file in a directory, for example c:\FitNesse. Extract the files from the fitSharp archive into a subdirectory in the same folder as fitnesse.jar called fitSharp.

Start FitNesse using java -jar fitnesse.jar -p 8080 where -p is the port number. FitNesse installs in a directory called FitNesseRoot. Browse to http://localhost:8080 and you should see the FitNesse front-end.

Creating a test fixture

To use FitNesse you’ll need to give a test fixture that FitNesse can execute. A test fixture is derived from one of the classes provided by the Fit framework. For this example, derive a test fixture from ColumnFixture. This will allow us to run the test case using a decision table with input and output values. Add a reference to both fit.dll and fitSharp.dll in your project.

namespace Humanresources.Domain
{
  public class EmployeeTests : fit.ColumnFixture
  {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get { return string.Concat(FirstName, " ", LastName); }
  }
}


Setting up the test case

To setup the test case, you will need to create a wiki-page. On the front page of FitNesse, click on Edit and enter a wiki-word with the name of the test case. A wiki-word is a word written in Pascal-case surrounded by square brackets, i.e. [EmployeeTests]. Click Save and then click on the question mark to go to the page and click on Edit.

To setup the test, you ‘ll need to define a couple of variables, they are

  1. location of the assembly under test;
  2. how to invoke the test runner;
  3. location of the test runner.
On edit page, enter the following:

!path C:\Projects\Experiments\HumanResources\HumanResources.Domain\bin\Debug\HumanResources.Domain.dll
!define COMMAND_PATTERN {%m -r fitnesse.fitserver.FitServer,c:\FitNesse\FitSharp\fit.dll %p}
!define TEST_RUNNER {c:\FitNesse\FitSharp\Runner.exe}

Click on Save. Next, you’ll need create the test inputs and expected output values:
|humanresources.domain.employeetests|
|firstname|lastname|fullname?  |
|John     |Lidin   |John Lidin |
|Joshua   |Cohen   |J Cohen    |
|Allan    |Butler  |A Butler   |

The first line specifies the class that is under test, the second line specifies the input values that are assigned to the properties with the same name and the following lines give the input and expected output values. The last column with the question mark is the evaluation column. This is a simple decision table. The last column name may also be the name of a method.

In the table, we are assigning the value John to FirstName property and Lidin to the LastName property. The expectation is that FullName is a concatenation of FirstName, a space and then followed by the LastName.

Before the test is run, you’ll need to tell FitNesse that this page is a page that contains tests and is not just a simple wiki-page. To change the page type to test page, click on Properties, select Test and then click Save.

An important thing to note here is that all the property names and class names are in lower case. This is intentional as Pascal-cased words are interpreted as wiki-words. For your own sanity keep them in lowercase.

Your page should now look like this:

Run the test case

Click on Test and you should see the following output:

The tests can also be executed from the command line, are you thinking what I’m thinking?

Troubleshooting

  • Fit.dll file load exception

System.IO.FileLoadException: Could not load file or assembly 'file:///c:\FitNesse\FitSharp\fit.dll'
or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)
File name: 'file:///c:\FitNesse\FitSharp\fit.dll' ---> System.NotSupportedException: An attempt was
made to load an assembly from a network location which would have caused the assembly to be sandboxed
in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy
by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please
enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.

To solve this issue, simply add a configuration file to the runner that you’re using. If you are using runner.exe then create a file called runner.exe.config and add the following text into runner.exe.config:

<configuration>
   <runtime>
      <loadFromRemoteSources enabled="true"/>
   </runtime>
</configuration>

References

[Cunn 07] Cunningham, Ward. Making Fixtures. Framework for Integrated Test. October 12, 2007. http://fit.c2.com/search.cgi?search=WelcomeVisitors


Unit testing with Jenkins

Posted in .net, rants, visual studio, windows by Sydney du Plooy on March 21, 2011

Continuing to setup a build for the first time with Jenkins there is, uh, another challenge. For some reason, I thought it clever to make use of MsTest. This works wonderfully on the development machine. But, of course, when it comes to the build server, you can expect all sorts of weirdness. For example, error CS0246: The type or namespace name ‘TestMethodAttribute’ could not be found…

We’re sorry, but our testing tools don’t come standard with the .NET Framework, or in any other way, except TFS and Visual Studio, unless you are willing to follow this brave soul. I share Derik Whittaker’s sentiment on the MsTest and build server issue.

This is another issue to me because MSTest is the ONLY test framework (for .Net) that I know of that does not run with a single DLL placed into the bin (or any other output directory).  I just have to ask the genius’ over in Redmond what the hell were they smoking when they decided to build MSTest.  It is pretty clear they had no prior knowledge of how to use the other tools such as NUnit, MBUnit or xUnit (I know, xUnit was not out yet).  I know this because of all the various testing frameworks MSTest is the one that does everything different.  You could argue they were on the cutting edge and were innovating, but I call BS on that.

This can be solved. So long MsTest… Hello NUnit!

Converting from MsTest to NUnit

Converting from MsTest is a simple case of find and replace of attributes. NUnit  has the nifty Assert.Catch<T> which beats MbUnit, MsTest and xUnit. xUnit comes with Assert.Throws<T> but cannot assert the exception message whereas NUnit can. No more [ExpectedException] attributes.

Integrating NUnit with the build file (which is MsBuild) is pretty easy:

<Exec Command=”$(NUnitFolder)\nunit-console-x86.exe [TestAssembly] /framework=net-4.0 /xml=$(TestResultsFolder)\TestResults.xml” />

A single Exec statement and out comes an Xml file. To keep the build server clean, I decided to add all the necessary files for unit testing into source control along with the project. The bare minimum files for running NUnit from the command line comes down to the following files:

  • nunit.core.dll
  • nunit.core.interfaces.dll
  • nunit.framework.dll
  • nunit.util.dll
  • nunit.console-runner.dll
  • nunit-console-x86.exe
  • nunit-agent-x86.exe
  • nunit-agent-x86.exe.config

To make it work on .Net Framework 4.0, you have to include the /framework=net-4.0 switch on the command line.

Setting up Jenkins with NUnit

Install the NUnit plugin for Jenkins, point it to your test results file and after a build you’ll get the summarised test results.  It’s a neat table with all the classes and their respective timings and so on.

Finally, I have a working build with unit testing. If only it had an installer…


AutoMocking with RhinoMocks and StructureMap

Posted in .net by Sydney du Plooy on December 13, 2010

Auto mocking is the process whereby mock objects are created and injected into an object. By using this technique we relieve ourselves from the burden of creating and injecting mocks manually. Consider the following test class that requires two dependencies; namely, IPropertyDependency and IConstructorDependency:

public class ClassToBeAutoMocked
{
	private IConstructorDependency _ConstructorInjectedDependency;

	public ClassToBeAutoMocked(IConstructorDependency dep)
	{
		_ConstructorInjectedDependency = dep;
	}

	private IPropertyDependency PropertyDependency
	{
		get;
		set;
	}

	public string PrintConstructorDependency()
	{
		return _ConstructorInjectedDependency.Print();
	}

	public string PrintPropertyDependency()
	{
		return PropertyDependency.Print();
	}
}

The one dependency is provided in the constructor and the other is injected via the private property. Out-of-the-box, StructureMap AutoMocker provides the ability to mock and inject the constructor dependency. Private properties, however, are not supported. This can be solved by means of an extension method applied to the RhinoAutoMocker type, for example:

public static class RhinoAutoMockerExtensions
{
	public static void RegisterPropertyDependency<TARGETCLASS>(this RhinoAutoMocker autoMocker, string propertyName) where TARGETCLASS : class
	{
		var propertyInfo = typeof(TARGETCLASS).GetProperty(propertyName,
			BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

		if (propertyInfo == null)
		{
			throw new ArgumentException(string.Format("Property {0} was not found on the type {1}",
				propertyName, typeof(TARGETCLASS).Name));
		}

		var propertyType = propertyInfo.PropertyType;
		var mockDependency = MockRepository.GenerateMock(propertyType, null);
		autoMocker.Inject(propertyType, mockDependency);
		propertyInfo.SetValue(autoMocker.ClassUnderTest, mockDependency, null);
	}
}

We now have the necessary pieces to get an auto mocked instance of ClassToBeAutoMocked.

Next, create an instance of the RhinoAutoMocker class with the concrete type, which will then create the constructor dependency mock and inject it. Because the private property dependency injection is not supported we have to tell the AutoMocker that we want the private property mocked and injected as well. We accomplish this by calling the extension method RegisterPropertyDependency with the name of the property that must be mocked. To obtain a reference to the generated mock we can call the Get method with the dependency type which will return the mock instance. We are then free to stub or set expectations on that dependency as required by our unit tests.

For example:

static void Main(string[] args)
{
	var mocks = new RhinoAutoMocker(MockMode.AAA);
	mocks.RegisterPropertyDependency("PropertyDependency");

	mocks.Get<IConstructorDependency>().Stub(x => x.Print()).Return("On fire with the constructor dependency!");
	mocks.Get<IPropertyDependency>().Stub(x => x.Print()).Return("On fire with the property dependency!");

	Console.WriteLine("Constructor dependency output: {0}", mocks.ClassUnderTest.PrintConstructorDependency());
	Console.WriteLine("Property dependency output: {0}", mocks.ClassUnderTest.PrintPropertyDependency());

	Console.ReadLine();
}

IConstructorDependency
Tagged with: ,

Mocking multiple interfaces using Rhino Mocks

Posted in .net, visual studio by Sydney du Plooy on June 6, 2010

A while back on StackOverflow I asked a question on how to create a mock object with Rhino Mocks that implements multiple interfaces. In other words, I want to generate a mock that implements more than one interface. This baffled me for a while and I was shown the light by one of my colleagues.

A multi-mock is created like so:

var mocker = new MockRepository();
var mock = mocker.CreateMultiMock<IPrimaryInterface>(typeof(IFoo), typeof(IBar));
mock.Expect(x => x.AnswerToUniverse()).Return(42);
mocker.ReplayAll();

Note the call to ReplayAll. Without this call the mock will not be setup with the intended values.

XML Intellisense for NHibernate

Posted in .net, visual studio by Sydney du Plooy on May 16, 2009

nhibernate-intellisenseUsing NHibernate requires the writing of some tedious XML-based configuration mapping files. Remembering all the tags and attributes can sometimes be overwhelming. Thankfully the contributors decided to include intellisense hints, which are in nhibernate-configuration.xsd and nhibernate-mapping.xsd.

In order to have the hints available in Visual Studio 2008 copy the files into C:\Program Files\Microsoft Visual Studio 9.0\XML\Schemas and restart Visual Studio.

Proxy class design

Posted in .net, aop by Sydney du Plooy on April 20, 2008

As part of designing our AOP.NET framework, I thought it best to start with the end in mind. What that entails is to figure out what our proxy class should look like. Let’s start with a simple interface and then design the proxy class according to the interface.

public interface IVehicle
{
  string Make{get;set;}
  void Start();
  void Stop();
}

If only all things in life could be so simple. What do we expect from our proxy class? First of all, it should proxy the call to the target instance.

But before the call is made to the target instance, it should first call our aspect class. Assume, for now, that our aspect just logs an entry whenever a call is made to one of the members.

That means that we would expect our proxy class to look something like this:

[Proxy]
public sealed class IVehicle_LogAspect_Proxy : IVehicle
{
  private IVehicle _TargetInstance;
  private ILoggerAspect _LoggerAspect;

  public IVehicle_LogAspect_Proxy(
    IVehicle targetInstance, ILoggerAspect loggerAspect)
  {
    _TargetInstance = targetInstance;
    _LoggerAspect = loggerAspect;
  }

  public string Make
  {
    get
    {
      _LoggerAspect.Log("Make.Get");
      return _TargetInstance.Make;
    }
    set
    {
      _LoggerAspect.Log("Make.Set");
      _TargetInstance.Make = value;
    }
  }

  public void Start()
  {
    _LoggerAspect.Log("Start");
    _TargetInstance.Start();
  }

  public void Stop()
  {
    _LoggerAspect.Log("Stop");
    _TargetInstance.Stop();
  }
}

First, there is a Proxy attribute applied to the proxy class. This is just to identify the class as a proxy type. Sometimes it might be necessary for calling code to know whether it is dealing with a real object or a proxy. The attribute facilitates this quite nicely.

Naming the type is a matter of concatenating the interface names, separated by underscores together with the aspect that is injected. Finally, we simply just add the word Proxy to the type name to help with identification.

After all that the constructor is next. The constructor plays a vital role in the proxy as it receives the reference to the target instance as well as the reference to the aspect instance. Both these references are assigned to private variables by the constructor.

As you can see, the aspect method is directly injected into the member, before the call is passed to the target instance.

The advantages of doing it this way are that all the heavy aspect code is outside of the proxy class, which makes it a lot simpler to write and maintain.

Now that we have an idea of what the proxy class should look like we will next look at the framework building blocks.

Tagged with: ,

Proxy aspect requirements

Posted in .net, aop by Sydney du Plooy on April 2, 2008

Problem:

A business software package has cross-cutting functionality across its domain objects. This leads to duplicated code and needs to be generalised.

Solution:

Produce a general proxy aspect framework for applying aspects to domain objects.

Note: The framework that we are going to construct is for a specific scenario and is not intended to compete with other aspect oriented frameworks out there. It is intended to demonstrate the principles and considerations that need to be taken into account when applying aspects to domain objects.

Prerequisite:

Every domain object must be defined by an interface.

Requirements:

At a high level our requirements for the proxy aspect framework are as follows:

  • Support multiple aspects per domain object;
  • Generated proxy must at least implement the domain objects interface;
  • Support aspects that need to implement their own interfaces on the proxy;
  • Collections must be applied the same aspects as the domain object it is defined on;
  • Proxy types must be cached;
  • Support the ability to place intercepting calls before and/or after the call to the target instance;
  • Must be able to save the assembly containing all proxy types;
  • Must be able to intercept methods, events and properties.

Next, we will discuss the framework design.

Tagged with: ,

Proxy aspect oriented approach

Posted in .net, aop by Sydney du Plooy on March 27, 2008

A proxy aspect approach is one of many approaches in Aspect Oriented Programming. The general idea behind AOP is to deal with the problem of cross-cutting concerns.

Let’s say you want to check the permissions of a user before executing a method (this is the type of aspect that we want to apply to our object). You can appreciate that when a system is beyond “Hello World!” that this can turn out to be quite a thing to remember and apply on every method.

To solve this problem we would need to inject this call into the methods where this security check needs to be done. This can be done in various ways, such as creating a proxy at runtime that performs the check or alter the assemblies with another tool after compilation.

Over the next couple of weeks, I will walk you through the requirements, design and construction of one of these approaches that I call; you guessed it; the proxy aspect approach.

Target instance with Proxy objectAt a high level, the idea is to create a proxy for every object that needs to have certain functionality executed as soon as, for example, a method is entered or a property is changed. In effect, the object will have multiple layers or proxies to which all calls; that are intended for the target instance; are directed.

One proxy is created for each aspect that is applied, and every proxy object carries a reference to the instance of the target instance. This target instance can either be another proxy object or the final domain object, say.

When the call is made to the proxy object it will execute the aspect code and then forward the call to the target instance. If the target instance is a proxy, the same process will happen again until it reaches the inner most target instance where the call is finally handled. If there are results that need to be returned, it passes back up through every proxy until it reaches the original caller.

Next, we’ll have a look at the requirements.

Tagged with: ,

Welcome

Posted in .net by Sydney du Plooy on March 24, 2008

Welcome to the Third Shelf!

The Third Shelf is the place where I put all those hardcore things that I have to deal with in programming, hardcore things such as aspect-oriented programming and all the other not-so-commonly-used stuff in the .NET framework.

I volunteered (blue pill or red pill?) to write an aspect-oriented subsystem, that applies aspects to business objects. Well, needless to say that I will never be the same person again! So, I decided to start this blog to talk about and show some of the intricacies, pit falls and abysses in programming aspect-oriented systems. I will also cover some other programming things, such as native assembler, .NET security, etc.

So, if you are willing to explore life on the wild-side of programming, stay tuned!

Comments Off

Follow

Get every new post delivered to your Inbox.

Join 144 other followers