Unit testing, your greatest maintenance tool

Methodology Add comments

Unit Testing, your greatest maintenance tool

Can I have transactions in Life 2.0?

I remember reading a cute cartoon a while back illustrating how nice it would be if real life let you have transactions. I remeber thinking at the time that it was a funny cartoon but didn’t give it much more thought.

Begin Transaction.

This morning I woke up and had a shower just like I do every morning. Afterwards I decided I needed to shave…but my shaver had gone dead. Plugs it in to recharge…oh well, I’ll just shave tomorrow. I am sure Visual Studio won’t mind my stubble for one day.

So I am ready to go with time to spare, what to do? I decide to boot up my old test machine and continue playing with Eclipse and Java; I may even have time to play a game of Risk. What’s this? BOOT DISK ERROR! Crap. Oh well, I’ll reformat the hard drive after work. Boot up my main PC and do some research for this article…yeah I should have been doing that anyways.

Time to go. Out to the car and hop in. Wow it sure rained a lot over night. BRRR BRRR BRRR. You’ve got to be kidding me! My car won’t start.

Rollback. Crap it didn’t work! Sigh. I call a tow truck instead.

Car analogy for unit tests

There are many times I wish real life could be maintained like a software program. In true SlashDot form I am going to try an make my case for Unit Testing with a car analogy (mind you probably a bad one).

To me writing software without writing unit tests is like me working on my car. I know the basics, change the oil, change the tires, and I can probably find my way around, eventually but when it gets down to the details I am scared to touch something because I don’t know what it will break. If I take part A off will I be able to put it back on and not break part B.

Making changes to untested code is much the same. You don’t really know what other parts of the program your changes are going to affect or ultimately break. That is why we end up with lots of redundant code and lots of repetition. Nobody wanted to risk breaking something by changing that method so they just created a new method that did basically the same thing. The end result is an API that is a mess.

A common argument against unit testing is that it takes extra time. This is true but if you stop to think about developing without unit tests for a moment you have to admit that unit tests will save you time in the long run. If you are not using unit tests how do you test your code? You fire up the UI and you input test data and check for the proper output. This process will take you far more time and will not clearly reveal any breaks code changes may have introduced.

With unit testing all this is fixed. You have a suite of tests that you can run and within a couple of minutes know with certainty that things are working as expected.

How do to write a unit test

It can be difficult to get started writing unit tests. Here are a couple of rules to help you get started on the right track.

1. Write the unit test first. What you want to do is write just enough logic (classes and interfaces) to let your code compile. This will force you to look at your code differently. Each piece of code will have a goal and the unit test will check to see if that goal is met or that it is handled properly if the goal is not met.

2. Keep your code loosely coupled. In order to properly, and easily, test your code it needs to be loosely coupled. This means you want to avoid writing methods and classes that depend on other methods and classes. There will be a certain amount of coupling but you want to keep it to a minimum. For example, you’ll obviously want to test your data access layer to ensure it is communicating with your database correctly. However, once you start testing the layer that talks to your data access layer you will want to simulate your data layer instead of actually using it. This is were Dependency Injection comes into play. We will be talking about this in a future post.

[TestFixture]
public class ExampleTests {
	[Test]
	public void GetEmployeesTest() {
		Company comapny = new Company(new FakeDataAccess());
		Assert.IsTrue(company.GetEmployees().Length > 0);
	}
}

public class Company {
	private IDataAccess dataAccess;
	//default data access layer
	public Company() : this(new RealDataAccess()) { }

	//allow dependancy injection of
	//desired data access layer
	public Company(IDataAccess dataAccess) {
		this.dataAccess = dataAccess;
	}

	public Employee [] GetEmployees() {
		return dataAccess.GetEmployees();
	}
}

public class FakeDataAccess : IDataAccess {
	public FakeDataAccess() { }

	public Employee [] GetEmployees() {
		Employee [] employees = new Employee [] {
			new Employee("Bob", "Hudson", "Accounting"),
			new Employee("Jim", "Dunn", "Accounting"),
			new Employee("Mark", "Johnson", "Accounting"),
			new Employee("Bill", "Parson", "Accounting")
		};
		return employees;
	}
}

This test may seem pointless but remember your real Data Access layer is also properly tested and this test is making sure your Company class is interacting with the Data Access Layer properly. This is a fairly obvious example but it illustrates the point I am trying to make.

Hopefully this gives you a taste of Unit Testing and helps get you started.

kick it on DotNetKicks.com

Popularity: 4% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

2 Responses to “Unit testing, your greatest maintenance tool”

  1. Anthony Alexander Says:

    I love bad analogies. I’m always giving them. Only special people seem to know what I’m getting at, the other people call me Jesus and bring me lots of water.

    This is crazy, I’m just rewriting an JS API because I’m too lazy to go throough 2000 lines of code. I always unit test but I was in a rush towards the end. I’m now unit testing and incooperating this into my debugger so I can more easily track my app in the future.

  2. Justin Says:

    Reality and deadlines tend to infringe upon our ideal programming environment. When this happens, sadly, some part of our application will suffer so it can be done on time.

    I am working toward the goal of a programming job where their are no clients and no insane deadlines and I can code in a complete utopian state…yes I would like to become a university professor. :D

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Login