JUnit

concepcionsockΛογισμικό & κατασκευή λογ/κού

15 Αυγ 2012 (πριν από 5 χρόνια και 3 μήνες)

279 εμφανίσεις

1

Unit Testing with JUnit

Meyer Tanuan,
BCS, MBA, MMath (CS)

2

Objectives



What is JUnit


Write a Test Case


Run a JUnit Test


Run a Test Suite



3

JUnit 3.8.1


JUnit 3.8.1


Available in NetBeans 5.x


Unit testing framework for Java


Open source, written in Java


http://www.junit.org/


Mainly for component/server
-
side testing


Not for GUI testing


Assert
-
driven testing


4

Write a Test Case


General Steps:


Test Case Class extends
junit.framework.TestCase


Constructor with
test name

string argument


Optional:

setUp() and tearDown()


Write a test for each functional unit


Use Assert.assertX() methods (e.g., assertEquals())


In
NetBeans 5.x
:


Generate skeleton test case class (e.g., MoneyTest)


junit
-
3.8.1.jar

is automatically added to Test Library


Details in JUnitNetBeans.htm tutorial

5

NetBeans Test Case Wizard

To generate test
cases:


Right
-
click Java
source


E.g., Money.java


Tools
-
> Create JUnit
Tests


Click Finish


6

Sample Test Method


Add the assertions


public void
testAdd()

{




Money m = new Money(12, "CAD");


Money instance = new Money(10, "CAD");




Money expResult = new Money(22, "CAD");


Money result = instance.
add
(m);



assertEquals
(expResult, result);


}

7

Unit Testing: Coding Tips


Method Call Coverage


All public methods must be called at least once


Indirect calls allowed


E.g., EmployeeTypePD.Find() calls
EmployeeTypeDA.Find()


Use Assertions


E.g., assertEquals(string, object, object) method


Consider use of Random class


To generate random numbers


Advanced Tip:


Check boundary conditions and failure scenarios
(forced
-
error tests)

8

Run a JUnit Test


Right
-
click the
test
case

class


E.g., MoneyTest.java


Run File


Result:
JUnit

tab:


Passed:


number of test cases
passed


Failed:


assertion that fails


Errors:


unexpected error (e.g.,
ClassCastException)

9

Run a Test Suite


Test Suite


To run multiple test
cases as a batch


NetBeans 5.x makes it
convenient to run all
the test cases


Run | Test
“exercise1”