JUNIT TEST CASE DOCUMENT
What is Junit
JUnit is an open source framework designed for the purpose of writing and running tests in the Java programming language. JUnit, originally written by Erich Gamma and Kent Beck, has been important in the evolution of test-driven development, which is part of a larger software design paradigm known as Extreme Programming(XP).
JUnit has a graphical user interface (GUI), making it possible to write and test source code quickly and easily
JUnit shows test progress in a bar that is normally green but turns red when a test fails. An ongoing list of unsuccessful tests appears in a space near the bottom of the display window. Multiple tests can be run concurrently
1. General
1.1 Unit Testing
A unit test is a piece of code written by a developer that exercises a very small, specific area of functionality of the code being tested. It can be used to ensure that existing functionality is still working after changes to the coding or the environment the program is running in.
A very important assumption of JUnit is that the all test can be performed in an arbitrary order hence each test should stand alone and not depend on another test.
1.2 Installation
Download JUnit4.x.jar from the JUnit website http://www.junit.org.
1.3 Add jar to classpath
The first thing we must do import junit.jar, so we have access to the testing framework.
Right-click on the project name, and choose Properties. In the tree on the left, select Java Build Path. Next, choose Add External JARs.. and browse to find junit.jar. It will be loacated in <eclipsedir>\plugins\org_junit_<version number>\junit.jar. Once you successfully import junit.jar, close the Properties page.
Coding Convention :
1. Name of the test class must end with “Test”.
2. Name of the method must begin with “test”.
3. Return type of a test method must be void.
4. Test method must not throw any exception.
5. Test method must not have any parameter.
2. JUnit with Eclipse
2.1. Preparation
Create a new project. Add a folder lib to this project. Copy your Junit jar into this folder and add it to the buld path of Eclipse.
Create a new source folder “junit” for your project. To do so right click mouse on your project, select properties and choose the java build path. Select the tab source code.
Press “Add folder” then then press “Create new folder”. Create the folder junit.
3.2. Create a normal class
Create the class “MyClass”. We will use this class for testing.
-
public class MyClass {
public int multiply(int x, int y) { return x / y; } }
3.3. Create a test class
Select your new class, right mouse click and select New ->JUnit Test case, change the source folder to JUnit
Press next and select the methods which you want to test.
Create a test with the following code.
-
import static org.junit.Assert.assertEquals; import org.junit.Test; public class MyClassTest { @Test public void testMultiply() { MyClass tester = new MyClass(); assertEquals(“Result”, 50, tester.multiply(10, 5)); } }
Right click on your new test class and select Run-As-> Junit Test.
The result should be the following. This is due to the fact that our multiplier class is currently doing division. Fix the bug and re-run test to get a green light.
Unit Testing Hibernate Mapping Configurations
We want to persist the following class to the database using Hibernate.
|
package com.emantras.ebook.domain; class Product { String productName; Long id; } |
Step 1: Write a Test
We will begin by writing a simple test that defines some of the behavior of our DAO: we simply create a Product, save it, and ensure that when we try to load it again, we get the same Product:
-
package com.emantras.ebook.domain.persist; import com.emantras.ebook.domain.Product;
import junit.framework.TestCase;
public class ProductDAOTest extends TestCase {
private ProductDAO productDAO = new ProductDAO();
public void testStoreRetrieve() {
Product product = new Product(“My product”);
long id = productDAO.store(product);
Product retrievedProduct = productDAO.get(id);
assertEquals(product, retrievedProduct);
assertNotSame(product, retrievedProduct);
}
}
Step 2: Make the Test Compile
This code fails to compile because I don’t have ProductDAO. Let’s create it:
-
package com.emantras.ebook.domain.persist; import com.emantras.ebook.domain.Product;
public class ProductDAO {
public long store(Product product) {
// TODO Auto-generated method stub
return 0;
}
public Product get(long id) {
// TODO Auto-generated method stub
return null;
}
}
Run the test. It fails because ProductDAO.get returns null.
Step 3: The DAO
To simplify the DAO implementation, we want to use Spring’s HibernateTemplate and inject it into the DAO. This is part of Spring’s ORM support. To include this functionality, you must add these files to your classpath: spring.jar, commons-logging.jar, and jta.jar. All of these files are available as parts of the Spring Framework download. We should also add hibernate.jar from the Hibernate download. We use HibernateTemplate in PersonDAOTest.setUp:
protected void setUp() throws Exception { HibernateTemplate hibernateTemplate =new HibernateTemplate(); productDAO.setHibernateTemplate(hibernateTemplate); } |
Add a setter for HibernateTemplate to the DAO, and it compiles. Of course, we still get the same error. To fix things, we have to implement the ProductDAO:
-
packagecom.emantras.ebook.domain.persist; import org.springframework.orm.hibernate3.HibernateTemplate;
import com.emantras.ebook.domain.Product;
public class ProductDAO {
private HibernateTemplate hibernateTemplate;
public long store(Product product) {
Long key =
(Long)hibernateTemplate.save(product);
return key.longValue();
}
public Product get(long id) {
return (Product)hibernateTemplate.get(
Product.class, new Long(id));
}
public void setHibernateTemplate (HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}
Running the test still produces an error, but this time it’s different: java.lang.IllegalArgumentException: No SessionFactory specified. From the stack trace, it’s obvious that we need to set the SessionFactory on the HibernateTemplate.
Step 4: Test Support for the HibernateTemplate
We’re going to create a SessionFactory in the test to give to the HibernateTemplate in the DAO. SessionFactory is part of Hibernate, so we have to add the core Hibernate .jar files (in addition to hibernate.jar, which Spring required) to the classpath: ehcache.jar, asm.jar, cglib.jar, common-collections.jar, and dom4j.jar. Since we’re using MS SQLSERVER as our database, we also have to add msbase.jar,mssqlserver.jar,msutil.jar to the classpath.
| protected void setUp() throws Exception {
Configuration configuration = new Configuration();
configuration.setProperty(Environment.DRIVER, “com.microsoft.jdbc.sqlserver.SQLServerDriver“); configuration.setProperty(Environment.URL, “jdbc:microsoft:sqlserver://SQLSERVERURL:PORT;DatabaseName=”DatabaseName“); configuration.setProperty(Environment.USER, “USER NAME“); configuration.setProperty(Environment.PASS, “PASSWORD“);
configuration.setProperty(Environment.DIALECT, SQLServerDialect.class.getName());
configuration.setProperty(Environment.SHOW_SQL, “true”);
configuration.addClass(Product.class);//To tell Hibernate about our Product class this.sessionFactory = configuration.buildSessionFactory(); HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory); productDAO.setHibernateTemplate(hibernateTemplate); this.session = SessionFactoryUtils.getSession(sessionFactory, true); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
} //This method called after every test method called protected void tearDown() throws Exception { TransactionSynchronizationManager.unbindResource(sessionFactory); SessionFactoryUtils.releaseSession(session, sessionFactory); }
|
The SHOW_SQL property is not required, but it will help you see what Hibernate is doing.
Create one function namely testStoreRetrieve() to get the product in ProductDAOTest class and Run the test class.
-
public void testStoreRetrieve() {Product product = new Product(“My product”); Long id = productDAO.store(product);
Product retrievedProduct = productDAO.get(id);
assertEquals(product, retrievedProduct);
assertNotSame(product, retrievedProduct);
}
It fails because Hibernate’s Session will ensure that only one instance of the “My Product” Product exists per session. We store and get the Product in the same session, so get returns the object we stored, and consequently assertNotSame fails. We need to do more work.
The Session Must Be Flushed
We saw that Hibernate ensures that two copies of the same data loaded in the same session resolve to the same object instance. This defeats the purpose of our test, as the object we save is never really retrieved from the data store. The cache of data in the session used to implement this is called Hibernate’s “first-level cache” or “session cache.”
To avoid getting retrievedProduct from the session cache, we have to ask Hibernate to clear it, which we can do by calling HibernateSession.clear. We have to make hibernateSession into an instance variable on the test so we can call it from the test method. Here is the final test:
-
public void testStoreRetrieve() {Product product = new Product(“My product”); Long id = productDAO.store(product);
hibernateTemplate.flush();
hibernateTemplate.clear();
Product retrievedProduct = productDAO.get(id);
assertNotSame(product, retrievedProduct);
assertEquals(product, retrievedProduct);
}
The test now passes, and we have a complete pattern for testing to ensure that our objects are persisted correctly