Monthly Archives: March 2013

Rolling rolling rolling – rolling back your data back in integration tests

A couple years ago, I had just started refactoring a legacy codebase by adding integration tests and was manually rolling back the database changes with several lines of handwritten sql deletes… (sorry). At Iowa Code Camp, I went to a Lee Brandt demo and looking at Lee’s demo code, I saw him using a transaction for the rollbacks and I hung my head in shame.

Try it like this:

using NUnit.Framework;
using System.Transactions;
namespace ProjectName.Tests.Integration
{
 [TestFixture]
 public class TestClass
 {
 private TransactionScope _transactionScope;
 [SetUp]
 public void SetUp()
 {
 _transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew);
 }
 //...Test some stuff, insert records, update records, etc...
 [TearDown]
 public void TearDown()
 {
 _transactionScope.Dispose();
 }
 }
}

Happy Testing,

Jim

Tips and Tricks: Start Windows service in a console window

I spend a lot of time writing windows services. If I had to install every one I worked on locally, my box would be terribly tired and a mess to boot.

Here is a way to  start a service in a console window without installing it on your box. Use this code in your Main. You will have to add the string[] args parameter if you do not have it.


static void Main(string[] args)
{
     //Start IOC Container Structuremap
     //http://structuremap.net/structuremap/
     _bootStrapper = new IocContainerBootstrapper();
     _bootStrapper.BootstrapStructureMap();

     //This configurator starts up log4net
     XmlConfigurator.Configure();

     Log.DebugFormat("The SweetService service bootstrapped '{0}':", ObjectFactory.WhatDoIHave());

     //Add '/console' to start options > Command Line Arguments in
     //your project properties
     //to get the service to start in console for debugging
     if (args.Length > 0 && args[0] == "/console")
     {
          Log.Debug("Starting this sweet service in Console mode for debugging");
          SweetService myService = new SweetService();
          myService.OnStart(args);
          Console.ReadKey();
     }
     else
     {
          ServiceBase[] servicesToRun = new ServiceBase[]
          { new SweetService() };
          Run(servicesToRun);
     }
}

Put  ‘console’ in your Start Options / Command line arguments in your visual studio project properties and set your project type to Console Application.

When you start the project now in a debugger, you will get a lovely console window with all your log4net output and you never had to install the service to work on it.

For this example, I am using log4net and I am using a colored console appender.  That makes the output in the console window great.

Enjoy,

Jim

My way or the highway! Activator.CreateInstance

I have an object that I always need created in one specific way. Its bits have to be loaded in a certain order and I want to control whenever that happens. Any other code requiring this object has to call my loader method.

I implement like this, using Activator.CreateInstance:

  1. Give the object a private constructor.
public class Monkey
{
     private Monkey()
     {}
}

2. In my loader class, I use Activator.CreateInstance like this:

(Monkey)Activator.CreateInstance(typeof(Monkey), true);

I also use this same activator code to spin up one of these monkeys in my test classes.

Entity Framework Validation Errors

Found this lovely little code snipped for interrogating the database validation errors sent back from an Entity Framework Save:


catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;

Enjoy,

-Jim

Test base class thanks to Rob Connery

I saw this great testbase class in a Tekpub video. Thank goodness for tekpub videos. I wish everything that I purchased was that pragmatic.

public class TestBase
{
	public static string GetCaller()
	{
		StackTrace stackTrace = new StackTrace();
		return stackTrace.GetFrame(2).GetMethod().Name;
	}

	public void IsPending()
	{
		Console.WriteLine("{0} -- pending", GetCaller());
	}

	public void Describes(string description)
	{
		Console.WriteLine("-----------------------");
		Console.WriteLine(description);
		Console.WriteLine("-----------------------");
	}
}