Unit Testing with JUnit

farrightSoftware and s/w Development

Aug 15, 2012 (4 years and 11 months ago)

303 views

Unit Testing with JUnit

Dan Fleck

Fall
2007

(For both CS
211
and
421


two birds… one lecture!
:
-
)

What is Unit Testing?


A procedure to validate
individual units of Source Code


Example: A procedure,
method or class


Validating each individual
piece reduces errors when
integrating the pieces together
later


Automated Unit Tests with
JUnit


Junit is a unit testing framework
for Java


Allows you to write unit tests in
Java using a simple interface


Automated testing enables
running and rerunning tests
very easily and quickly

An example unit test

public void testCellChangePropagates() {

Spreadsheet sheet =





new Spreadsheet();



sheet.put("A
1
", "
5
");




sheet.put("A
2
", "=A
1
");



sheet.put("A
1
", "
10
");




assertEquals("
10
",sheet.get("A
2
"));

}

Junit with Netbeans

1.
New File

2.
Choose file type: Junit

3.
Choose Test for Existing Class

4.
Junit test with all stubs
created for that class

5.
Fill in the individual tests

6.
Run Tests (Netbeans options)

Coverage Analysis


Determining which lines of
code your tests have exercised
and which they have not


Allows you to detect if your unit
tests (or system tests) are
adequately covering all
possibilities or not


This is just one way to test

Coverage Analysis with
Netbeans


Install Unit Test Code Coverage
Viewer module


Write a Unit Test


Run test and view highlighted
code

A simple test to dynamically
cover your code:


public void testMain() {



SuDoku sFrame = new SuDoku();



while (sFrame.isDisplayable()) {


try {




Thread.sleep(
100
);



} catch (Exception e) {







e.printStackTrace();



}


}


Assert.assertEquals(true,true);


}

Summary


Unit tests can help test the
details of your program


Automated unit tests provide
constant visibility and easy
retesting


Test coverage supplies
valuable information when
running both unit tests and
system tests