Showing posts with label JUnit basic. Show all posts
Showing posts with label JUnit basic. Show all posts

Wednesday, June 10, 2009

JUnit

JUnit

JUnit is an open source unit testing framework for writing repeatable tests.


Site: http://junit.org/


Test

Simple JUnit 4 Test:

@Test public void simpleAdd() {

assertTrue(2+2,4);

}


Fixtures

Test fixtures are the objects which are shared by multiple tests.

e.g. Database connection, Class instances

public class MoneyTest {

private Person person;


@Before public void setUp() {

person= new Person("Ritesh", 24, true);

}

}


Exceptions

For testing functions which need to be tested for expected Exceptions:

@Test(expected= IndexOutOfBoundsException.class) public void empty() {

new ArrayList<Object>().get(0);

}

Running Test

  • JUnit Console tool:

org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...);

  • Eclipse inbuilt tool

Test Suite

Create empty class with following annotations:

@RunWith(Suite.class)

@SuiteClasses({

AdditonTest.class,

MultiplicationTest.class

})

public class AllRetrivalTests {

}


Testing Web Application

Cactus is an open source JUnit extension for testing Web application i.e. Servlet and JSP’s.

Struts:

  1. http://www.onjava.com/pub/a/onjava/2004/09/22/test-struts.html
  2. http://depressedprogrammer.wordpress.com/2007/06/18/unit-testing-struts-2-actions-spring-junit/
  3. http://www.rkcole.com/articles/struts/crudTutorial/step1.html#createUnitTestClasses

Hibernate:

  1. http://today.java.net/pub/a/today/2005/10/11/testing-hibernate-mapping.html

Reference:

  1. http://junit.sourceforge.net/
  2. http://www.ibm.com/developerworks/java/library/j-junit4.html?ca=dgr-lnxw01JUnit4

Usage

  • Tests should be written before the code. Test-first programming.
  • Test only the code that can break
  • Run unit tests often, ideally every time you change the code

Was the information useful?

Followers