Title: Topic: Junit
1Topic Junit Presenters Govindaramanujam, Sama
Jansen, Erwin
2- What is Junit?
- It is a simple framework to write repeatable
tests. - How to use it?
- When you need to test something, here is what you
do - Create an instance of TestCase
- Create a constructor which accepts a String as a
parameter and passes it to the superclass. - Override the method runTest()
- When you want to check a value, call assertTrue()
and pass a boolean that is true if the test
succeeds
3A Simple Example To test that the sum of two
Moneys with the same currency contains a value
which is the sum of the values of the two Moneys,
write public void testSimpleAdd() Money
m12CHF new Money(12, "CHF") Money m14CHF
new Money(14, "CHF") Money expected new
Money(26, "CHF") Money result
m12CHF.add(m14CHF) assertTrue(expected.equals(
result))
4- What is a text fixture?
- If tests need to run against the background of a
known set of objects, the set of objects is
called a test fixture. - When you have a fixture, here is what you do
- Create a subclass of TestCase
- Create a constructor which accepts a String as a
parameter and passes it to the superclass. - Add an instance variable for each part of the
fixture - Override setUp() to initialize the variables
- Override tearDown() to release any permanent
resources you allocated in setUp
5An Example To write several test cases that want
to work with different combinations of 12 Swiss
Francs, 14 Swiss Francs, and 28 US Dollars, first
create a fixture public class MoneyTest extends
TestCase private Money f12CHF
private Money f14CHF private Money
f28USD protected void setUp()
f12CHF new Money(12, "CHF") f14CHF new
Money(14, "CHF") f28USD new Money(28,
"USD")
6- How do you write and invoke an individual test
case when you have a Fixture? - Here is what you do
- Write the test case method in the fixture class.
Be sure to make it public, or it can't be invoked
through reflection. - Create an instance of the TestCase class and pass
the name of the test case method to the
constructor
7How do you run several tests at once? Use a Test
Suite. An Example To create a suite of two test
cases and run them together, execute TestSuite
suite new TestSuite() suite.addTest(new
MoneyTest("testMoneyEquals")) suite.addTest(new
MoneyTest("testSimpleAdd")) TestResult result
suite.run()
8How do you run your tests and collect their
results? Use a Test Runner An Example public
static Test suite() TestSuite suite new
TestSuite() suite.addTest(new
MoneyTest("testMoneyEquals"))
suite.addTest(new MoneyTest("testSimpleAdd"))
return suite
9JUnit provides both a graphical and a textual
version of a TestRunner tool. Start it by typing
java junit.awtui.TestRunner
Or
junit.swingui.TestRunner.
10- References
- junit.org - a site for software developers using
JUnit.