Test Driven Development in Java

SHARE & COMMENT :

Introduction

Test driven development a software development methodology which ensure at an early stage that the code written by the developer is what it is supposed to do, which eventually improves the design, produces testable code and reduces the amount of re-engineering that would have been necessary because of the wrong assumptions. Test Driven Development (TDD) is widely used in extreme Programming. This document gives an overview on TDD.

also read:

Drawback with the traditional testing

  • Testing Poorly Written Code: Defects with the software system makes it unusable and the approach followed for getting rid of defect is by testing the code and trying to break it. But testing once the code is frozen is a lengthy, slow and a costly process to further develop it.
  • Maintenance: Poorly written code apart from having a bad design is also difficult to change, since it’s difficult to understand the code. Even if the modifications are incorporated there can be some sideeffects on other parts of the functionality.
  • Failure to meet the requirement: Failing to deliver as per the requirement of the customer on time would not only lead to a delayed delivery but also extends the deadline , the requirement of the customer also changes during this period and the process keeps on going

The Solution -Test Driven Development(TDD)

What is TDD?

“Before we write the code, think about what your code will do.Write a test that will use the methods that hasn’t been written yet.”

TDD completely twirl traditional development around Kent Beck, had popularized TDD in eXtreme Programming he defines 2 simple rules one is write new business code only when your automated test has failed. second ,as you keep changing remove any duplication that you find. Beck also explained how these two simple rules generate complex individual and group behavior

On a lower level we test-drive code using the technique we call TDD,on a higher level-that of features and funcunality of the system -we test drive the system using a similar technique we call a acceptance TDD.

The advantage of TDD is

High Quality with TDD:as this way of programming that encourages good design and is a disciplined process that helps us avoid programming errors.This is achieved by making us write small,automated tests,which eventually build up a small alarm system for protecting our code from regression.

The short development cycle that TDD promotes is a well geared toward writing high-quality code from the start. Due to the short cycle we deviate from the traditional development methodology.

i.e. Design->Implement->Test the implementation

instead we follow

Test->Code->Refractor

i.e write the test first and then write the code to see that the test passes and finally refractor to remove any duplication and taking the code toward the best design we can imagine.

Improves the Quality:Quality of a s/w can be measured in terms of the degree to which the s/w fulfils the users requirement as well as in terms of the internal quality of the software that translates to external qualities like cost of development ,maintenance etc.by following TDD ,its assured that there is no code in the system that is developed that is unwanted.

Less time in Fixing code: Finding and fixing defects at an early stage is what we achieve practicing TDD which invariably reduces the development time.

Acceptance TDD

TDD helps us to write code having high technical quality .since the correctness of the code we develop with TDD is for isolated block of code rather than for the feature or functionality of the software .Acceptance TDD bridges the gap between the coder and the customer .Acceptance TDD tests the behaviour of the system rather than an single Object.

TDD Cycle

As already discussed when following the TDD approach we write the test first and then code and finally, design also
called the refractor phase as shown in figure-1

Test :When we are writing the test ,we are actually designing the API envisioning what the functionality of our code could be.

Code: When we talk about code we try to write the code to ensure that our test pass, when the test passes it doesn’t mean that the code written by us is optimal,but we keep improving the design in the last step Refractor.

Refractor: In the final step we look into how we can make our code more optimal and invariantly the design as well.

Tools of TDD

Just like any other type of development we require tools and technique for TTD too and there are 3 different categories

  • Unit Testing Framework
  • Continuous integration and builds
  • Code coverage

Unit testing framework for TDD :There are frameworks available for unit testing our code.One of the most popular framework for Java is JUnit built around XUnit which provides us with base classes which is extended for writing our tests,different test runners that helps us execute and collect the test results.

When it come to framework for acceptance TDD we don’t have a base framework as such since the idea of test-driving on feature level is relatively new.

As we keep constantly changing our code as we try to improve it, there is constant requirement to integrate their changes more often thus we need to have to adopt a process to synchronize our changes to the source storehouse. Apart from integration we also need to check that the integrated source code works too.A common practice is to run a relevant subset of all test before checking in their changes and to delegate the running of the full test suite to a dedicated build server also known as Continuous build server which keeps polling for any changes in the source repository and only tests those relevant portions rather than testing the entire code which would take lot of time.There are tools available to write the build servers.

There are tools available to measure code coverage or test coverage which detect any anomalies in our code in terms of wrong usage of constructs etc.Code coverage measures how thoroughly the test cases look through our production code.

Examples of Unit Testing Framework

JUnit

  • Expected results can be tested with the help of assertions
  • During development of the applications itself we can code and test
  • Easily Understandable
  • Provision of a GUI enables the writing and testing of the code more easily and quickly
  • Helps the developer to write and execute repeatable automated tests
  • Eclipse IDE comes with both JUnit and a plug-in for creating and working with JUnit tests
  • Junit today is a de facto standard framework for developing unit tests in Java

Mock Objects

  • Developing around dependencies i.e. code depending on classes that have not yet been developed
  • Mock Objects can be used to simulate the functionality of a production class.
  • Use a mock object framework that allows you to specify the behavior of the dependant class through API.
  • How Mock objects are used
    • mock object instance to be created
    • name of the mock object to be set
    • expected behavior of the mock object to be set
    • Use the mock object as a parameter in the test
    • At the end of the test,verify the mock object was used correctly.
  • The idea behind all Mock Object frameworks is the same.
Eg: EasyMock a framework 
	//instance of Mock Object
	Interface is the name of the un implemented class.All the methods of the class is declared in 
	an interface.
	MockControl control= MockControl.createControl(interface.class);
	//Getting a mock object.i.e an dummy implementation of our interface
	Interfaceimpl mockimpl=(interfacename) control.getMock();
	//Training the mock object .i.e  for a given method if a certain input is passed what should be expected
	Mockimpl.method1(“arguments”);
	Control.setReturnValue(“return value”);
	//using the mock object
	Control.replay();
	//verifying the mock object
	Control.verify();

HttpUnit

  • HttpUnit is a framework based on JUnit, which allows the creation of automated test cases for Web applications.
  • It is suitable for the implementation of automated functional tests, or acceptance tests

Cactus

  • Cactus is a simple test framework that implements an in-container strategy, meaning that tests are executed in the container .
  • Cactus is a framework for unit testing server-side java code (like Servlets, EJBs, Tag Libs, Filters, …).
  • HttpUnit does not do an in container testing.

StrutsTestCase

  • unit testing a part of your Struts application
  • StrutsTestCase extends the JUnit framework to allow testing the Action class.StrutsTestCase is an open source project from SourceForge.
  • It even offers two approaches: one that uses the servlet container and utilizes Cactus framework from Jakarta, and one that simulates the container.

Summary

TDD is an approach to build working software from day one. Enables developers to write reliable & error free code at the same time .It is a technique quickly being adopted by Agile software developers

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better