unit tested functionality

Unit Tests – A Crash Course

Unit testing is about writing a separate piece of code in addition to your production code. The purpose of this non-production code (or unit tests) is to indicate whether or not the production code works as intended.

The phrase “unit testing” means that we identify a coherent unit of code and test that in isolation. A “unit” is often a single class, but not necessarily; it can be a group of classes working together, as much as a single method.

A Quick Example

As an example, suppose you’re writing a mathematics library and you want to make sure that the division function actually takes one number and divides it by another. You might implement this function as follows:

public class Mathematics {

	public static float divide(float a, float b) {
		return a / b;
	}
}

Assuming your project has all the required dependencies, the unit test you write might look something like this:

public class MathematicsTest {

	@Test
	public void dividesAByB() {
		float result = Mathematics.divide(9, 3);
		assertThat(result, is(3));
	}
}

Whenever MathematicsTest.dividesAByB() is run as a unit test, it will try to divide 9 by 3 using the library function you wrote. If the function works, the test will pass. If somebody (including yourself) changes the divide function at some point, the unit test will most likely fail the next time it’s run.

Writing Unit Tests

There are different approaches to writing unit tests. Some programmers like to write the unit tests after the target functionality has been implemented, while others prefer to write the unit tests first, and then to let those unit tests drive the design of the production code. The latter approach is what’s commonly referred to as test-driven development, or TDD, and is by many regarded as the best way to achieve and maintain clean code in their projects.

Summary

I’ve just given you a very small glimpse of what unit tests are and why we use them. There is much more to say on the subject than what I’ve mentioned here, and I’ll probably cover some of it in future blog posts. Until then, you now have enough to go on if you want to study it on your own in more detail.

Thomas Kåsene

Thomas Kåsene

Thomas is a certified Java professional and focuses on writing clean code that is easy to read, unit test and maintain. In addition to having worked on large enterprise applications, he's also developed several Android apps and websites through the years. In 2011, Thomas graduated with a Bachelor of Science in IT from the then Norwegian School of Information Technology.

More Posts - Website

Follow Me:
TwitterLinkedIn