Unit Testing - Junit Approach

Unit Testing involves testing unit components or modules of Code and validating that they work properly. It’s a proactive procedure, which means that code written by developers needs to be unit tested at the unit level. All test cases are independent of each other and are to be written and executed by development team.

Prior fixing a bug, write a unit test to reproduce it. When the bug is fixed, verify the fix using the unit test. All methods need to be covered by the tests. The tests need to covers all paths through the unit. Unit Tests will ensure errors are picked up at the earlier stage and will facilitate easy integration.

Unit Testing Process

The figure below illustrates the Unit Testing Procedure and it encourages developers to write test cases before they start developing their use cases.

Unit test life cycle

Guidelines for Unit Test Cases

Unit Testing Tools
Consider a combination of JUnit and EasyMock to write Unit Test Cases. These tools are integrated with Eclipse (hopefully with Intellij) to merge unit tests with the development process.

Unit Testing Framework - JUnit
JUnit provides a Java based framework for unit testing. In order to setup JUnit one has to download the junit.jar file which is freely downloadable and append it to your classpath. JUnit will be integrated with the Eclipse development environment.

EasyMock
EasyMock, an open source library provides an easy medium to generate mock objects for a given interface. This facilitates running Junit tests for individual classes with the collaborators being simulated with Easy Mock Objects.

To get a Mock Object, we need to perform the following steps:

import junit.framework.TestCase;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.reset;
import static org.easymock.EasyMock.verify;

public class UserServiceImplTest extends TestCase {
private UserDao userDaoMock;
private UserService us;
public void setUp() throws Exception {

// 1. create the mock for our DAO
userDaoMock = createMock(UserDao.class);

// 2. create an instance of the class under test
us = new UserServiceImpl();

// 3. wire test object and mock
us.setUserDao(userDaoMock);

}

/**
* after each test method call the mock has to be reset
*/
public void tearDown() throws Exception {
reset(userDaoMock);
}
}

Written by Ravi Nallakukkala on April 8th, 2007 with no comments.
Read more articles on Design.

Related articles

No comments

There are still no comments on this article.

Leave your comment...

If you want to leave your comment on this article, simply fill out the next form:




You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> .