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:
- http://www.onjava.com/pub/a/onjava/2004/09/22/test-struts.html
- http://depressedprogrammer.wordpress.com/2007/06/18/unit-testing-struts-2-actions-spring-junit/
- http://www.rkcole.com/articles/struts/crudTutorial/step1.html#createUnitTestClasses
Hibernate:
Reference:
- http://junit.sourceforge.net/
- 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
No comments:
Post a Comment