Test Driven Development Example

Do you like this?

Summary:
This is a very simple example to demonstrate how Test Driven Development is utilised in the production environment. By going through this, you can get a basic understanding of how to apply this approach.


Content:

Just to recap the basic principle of TDD, I'm listing the steps of its workflow below:
1) write a test case 2) run the test 3) if it fails, refactor the production code 4) re-run the test and go back to step 3 (if required) until the test case is passed 5) repeat the whole process

To demonstrate the process, I'm going to use Java and Eclipse as my programming language and the tool to develop the code. Assume our requirement is:

Write a method to sum up 2 or more integer numbers

Let's create a test case:
Test Driven Development Example 1

The class MyClass doesn't exist yet so the Eclipse IDE is showing errors below:
Test Driven Development Example 2

Create MyClass as an empty class
Test Driven Development Example 3

In Java, JUnit is used for unit testing. Let's run the test
Test Driven Development Example 4

The test has passed. Bear in mind, both MyClass and TestMyClass classes are empty
Test Driven Development Example 5

Write the expected result which you want to test the class MyClass against
Test Driven Development Example 6

There is no method sumUp() yet so we have to write a mockup method in MyClass
Test Driven Development Example 7

The test case still failed because the method sumUp() always returns 0
Test Driven Development Example 8

Re-implement the code
Test Driven Development Example 9

The test case has passed now
Test Driven Development Example 10

Now we want to check if the sumUp() method can check overflow
Test Driven Development Example 11

We haven't implemented this behaviour in sumUp() so it failed again
Test Driven Development Example 12

We now have to put a check condition in sumUp() for this situation
Test Driven Development Example 13

Now all the test cases have passed
Test Driven Development Example 14

 
comments powered by Disqus