Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write unit test first and code later?

I am new to unit testing and have read several times that we should write unit test first and then the actual code. As of now , i am writing my methods and then unit test the code.

If you write the tests first...

You tend to write the code to fit the tests. This encourages the "simplest thing that solves the problem" type development and keeps you focused on solving the problem not working on meta-problems.

If you write the code first...

You will be tempted to write the tests to fit the code. In effect this is the equivalent of writing the problem to fit your answer, which is kind of backwards and will quite often lead to tests that are of lesser value.

Sounds good to me. However, How do i write unit tests even before having my code in place? Am i taking the advice literally ? Does it means that i should have my POCO classes and Interfaces in place and then write unit test ?

Can anyone explain me how this is done with a simple example of say adding two numbers?

like image 774
NoobDeveloper Avatar asked Sep 25 '13 11:09

NoobDeveloper


1 Answers

It's simple really. Red, Green, Refactor.

Red means - your code is completely broken. The syntax highlighting shows red and the test doesn't pass. Why? You haven't written any code yet.

Green means - Your application builds and the test passes. You've added the required code.

Refactor means - clean it up and make sure the test passes.

You can start by writing a test somewhat like this:

[TestMethod]
public void Can_Create_MathClass() {
    var math = new MathClass();
    Assert.IsNotNull(math);
}

This will fail (RED). How do you fix it? Create the class.

public class MathClass {
}

That's it. It now passes (GREEN). Next test:

[TestMethod]
public void Can_Add_Two_Numbers() {
    var math = new MathClass();
    var result = math.Add(1, 2);
    Assert.AreEqual(3, result);
}

This also fails (RED). Create the Add method:

public class MathClass {
    public int Add(int a, int b) {
        return a + b;
    }
}

Run the test. This will pass (GREEN).

Refactoring is a matter of cleaning up the code. It also means you can remove redundant tests. We know we have the MathClass now.. so you can completely remove the Can_Create_MathClass test. Once that is done.. you've passed REFACTOR, and can continue on.

It is important to remember that the Refactor step doesn't just mean your normal code. It also means tests. You cannot let your tests deteriorate over time. You must include them in the Refactor step.

like image 110
Simon Whitehead Avatar answered Sep 28 '22 08:09

Simon Whitehead