Java Foundations - University of Mississippi

Download Report

Transcript Java Foundations - University of Mississippi

Chapter 12
Introduction to
Collections - Stacks
Collections
• A collection is an object that holds and organizes
other objects
• It provides operations for accessing and
managing its elements
• Many standard collections have been defined
over time
• Some collections are linear in nature, others are
non-linear
• http://docs.oracle.com/javase/tutorial/collection
s/interfaces/index.html
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 2
Linear and Non-Linear Collections
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 3
The Java Collections API
• The Java Collections API is a subset of the Java
API
• As we explore a particular collection, we will also
examine any support provided in the Collections
API for that collection
• However, even if that support is provided, we
may still “reinvent the wheel” in order to learn
how these collections are implemented.
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 4
Focus on
Linear
Collections
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
5
Linear Collection: Queue
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
14 - 6
Linear Collection: List
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 7
Linear Collection: Stack
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 8
Review of Abstraction
• An abstraction hides details to make a concept
easier to manage
• All objects are abstractions in that they provide
well-defined operations (the interface)
• They hide (encapsulate) the object's data and the
implementation of the operations
• An object is a great mechanism for implementing
a collection
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 9
Refinement of Terms
• The distinction between the terms data type,
ADT, data structure, and collection is sometimes
blurred in casual use
– A data type is a group of values and the operations
defined on those values
– An abstract data type (ADT) is a data type that isn't
pre-defined in the programming language
– A data structure is the set of programming constructs
and techniques used to implement a collection
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 10
Collection Abstraction
• A class that uses a collection interacts with it
through a particular interface
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 11
Interface: Queue
What types of applications would use a queue?
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
14 - 12
Interface: List
What types of applications would use a list?
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 13
Another type of linear collection: Stacks
• A stack is a classic collection used to help solve
many types of problems
• A stack is a linear collection whose elements are
added in a last in, first out (LIFO) manner
• That is, the last element to be put on a stack is
the first one to be removed
• Think of a stack of books, where you add and
remove from the top, but can't reach into the
middle
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 14
Linear Collection: Stack
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 15
Stack Operations
• Some collections use particular terms for their
operations
• These are the classic stack operations:
What types of applications would use a Stack?
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 16
Relationships
• Note that Queues and Stacks are both linear
collections.
• Also note that they are time-ordered collections.
• What relationship do the elements of a
hierarchical collection have?
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 17
Object-Oriented Concepts
• Several OO concepts, new and old, will be
brought to bear as we explore collections
• We'll rely on type compatibility rules, interfaces,
inheritance, and polymorphism
• Review these concepts as necessary
• We'll also rely on a programming mechanism
introduced in Java 5, generics, which are
particularly appropriate for implementing
collections
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 18
Generics
• Suppose we define a stack that holds Object
references, which would allow it to hold any object
• But then we lose control over which types of
elements are added to the stack, and we'd have to
cast elements to their proper type when removed
• A better solution is to define a class that is based on
a generic type
• The type is referred to generically in the class, and
the specific type is specified only when an object of
that class is created
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 19
Generics
• The generic type placeholder is specified in angle
brackets in the class header:
class Box<T>
{
// declarations and code that refer to T
}
• Any identifier can be used, but T (for Type) or E
(for element) have become standard practice
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 20
Generics
• Then, when a Box is needed, it is instantiated
with a specific class instead of T:
Box<Widget> box1 = new Box<Widget>();
• Now, box1 can only hold Widget objects
• The compiler will issue errors if we try to add a
non-Widget to the box
• And when an object is removed from the box, it
is assumed to be a Widget
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 21
Generics
• Using the same class, another object can be
instantiated:
Box<Gadget> box2 = new Box<Gadget>();
• The box2 object can only hold Gadget
objects
• Generics provide better type management
control at compile-time and simplify the use of
collection classes
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 22
Stack Application
Evaluating a Postfix Expression
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 23
Postfix Expressions
• Let's see how a stack can be used to help us solve
the problem of evaluating postfix expressions
• A postfix expression is written with the operator
following the two operands instead of between
them:
15 8 is equivalent to the traditional (infix) expression
15 - 8
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 24
Postfix Expressions
• Postfix expressions eliminate the need for
parentheses to specify the order of operations
• Infix expression: 15 – 8
– Equivalent postfix form: 15 8 -
• Infix: (3 * 4 – (2 + 5)) * 4 / 2
– Equivalent postfix form: 3 4 * 2 5 + – 4 * 2 /
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 25
Evaluating Postfix Expressions
• We'll use a stack as follows to evaluate a postfix
expression:
– Scan the expression left to right
– When an operand is encountered, push it on the
stack
– When an operator is encountered, pop the top two
elements on the stack, perform the operation, then
push the result on the stack
• When the expression is exhausted, the value on
the stack is the final result
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 26
Evaluating Postfix Expressions
• Here's how the stack changes as the following
expression is evaluated:
7 4 -3 * 1 5 + / *
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 27
Class Exercise
Evaluate the following Postfix expressions:
51–3*
513*–
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 28
import java.util.Scanner;
/**
* Demonstrates the use of a stack to evaluate postfix expressions.
*
* @author Java Foundations
* @version 4.0
*/
public class PostfixTester
{
/**
* Reads and evaluates multiple postfix expressions.
*/
public static void main(String[] args)
{
String expression, again;
int result;
Scanner in = new Scanner(System.in);
do
{
PostfixEvaluator evaluator = new PostfixEvaluator();
System.out.println("Enter a valid post-fix expression one token " +
"at a time with a space between each token (e.g. 5 4 + 3 2 1 - + *)");
System.out.println("Each token must be an integer or an operator (+,-,*,/)");
expression = in.nextLine();
result = evaluator.evaluate(expression);
System.out.println();
System.out.println("That expression equals " + result);
System.out.print("Evaluate another expression [Y/N]? ");
again = in.nextLine();
System.out.println();
}
while (again.equalsIgnoreCase("y"));
}
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 29
import java.util.Stack;
import java.util.Scanner;
/**
* Represents an integer evaluator of postfix expressions. Assumes
* the operands are constants.
*
* @author Java Foundations
* @version 4.0
*/
public class PostfixEvaluator
{
private final static char ADD = '+';
private final static char SUBTRACT = '-';
private final static char MULTIPLY = '*';
private final static char DIVIDE = '/';
private Stack<Integer> stack;
/**
* Sets up this evalutor by creating a new stack.
*/
public PostfixEvaluator()
{
stack = new Stack<Integer>();
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 30
/**
* Evaluates the specified postfix expression. If an operand is
* encountered, it is pushed onto the stack. If an operator is
* encountered, two operands are popped, the operation is
* evaluated, and the result is pushed onto the stack.
* @param expr string representation of a postfix expression
* @return value of the given expression
*/
public int evaluate(String expr)
{
int op1, op2, result = 0;
String token;
Scanner parser = new Scanner(expr);
while (parser.hasNext())
{
token = parser.next();
if (isOperator(token))
{
op2 = (stack.pop()).intValue();
op1 = (stack.pop()).intValue();
result = evaluateSingleOperator(token.charAt(0), op1, op2);
stack.push(new Integer(result));
}
else
stack.push(new Integer(Integer.parseInt(token)));
}
return result;
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 31
/**
* Determines if the specified token is an operator.
* @param token the token to be evaluated
* @return true if token is operator
*/
private boolean isOperator(String token)
{
return ( token.equals("+") || token.equals("-") ||
token.equals("*") || token.equals("/") );
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 32
/**
* Peforms integer evaluation on a single expression consisting of
* the specified operator and operands.
* @param operation operation to be performed
* @param op1 the first operand
* @param op2 the second operand
* @return value of the expression
*/
private int evaluateSingleOperator(char operation, int op1, int op2)
{
int result = 0;
switch (operation)
{
case ADD:
result = op1
break;
case SUBTRACT:
result = op1
break;
case MULTIPLY:
result = op1
break;
case DIVIDE:
result = op1
}
+ op2;
- op2;
* op2;
/ op2;
return result;
}
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 33
Postfix Evaluator UML
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 34
Stacks in the Java API
• The postfix example uses the java.util.Stack class,
which has been part of the Java collections API
since Java 1.0.
• It implements the classic operations, without any
separate interfaces defined
• http://docs.oracle.com/javase/8/docs/api/java/u
til/Stack.html
– There is not a lot of consistency regarding how
collections are implemented in the Java API.
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 35
A Stack Interface
• Although the API version of a stack did not rely
on a formal interface, we will define one for our
own version
• To distinguish them, our collection interface
names will have ADT (abstract data type)
attached
• Furthermore, our collection classes and
interfaces will be defined as part of a package
called jsjf
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 36
A Stack Interface
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 37
package jsjf;
/**
* Defines the interface to a stack collection.
*
* @author Java Foundations
* @version 4.0
*/
public interface StackADT<T>
{
/**
* Adds the specified element to the top of this stack.
* @param element element to be pushed onto the stack
*/
public void push(T element);
/**
* Removes and returns the top element from this stack.
* @return the element removed from the stack
*/
public T pop();
/**
* Returns without removing the top element of this stack.
* @return the element on top of the stack
*/
public T peek();
/**
* Returns true if this stack contains no elements.
* @return true if the stack is empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
* @return the number of elements in the stack
*/
public int size();
/**
* Returns a string representation of this stack.
* @return a string representation of the stack
*/
public String toString();
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 38
Implementing a Stack with an Array
• Let's now explore our own implementation of a
stack, using an array as the underlying structure
in which we'll store the stack elements
• We'll have to take into account the possibility
that the array could become full
• And remember that an array of objects really
stores references to those objects
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 39
Implementing Stacks with an Array
• An array of object references:
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 40
Exceptions
• When should exceptions be thrown from a
collection class?
• Only when a problem is specific to the concept of
the collection (not its implementation or its use)
• There's no need for the user of a collection to
worry about it getting "full," so we'll take care of
any such limitations internally
• But a stack should throw an exception if the user
attempts to pop an empty stack
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 41
Managing Capacity
• The number of cells in an array is called its
capacity
• It's not possible to change the capacity of an
array in Java once it's been created
• Therefore, to expand the capacity of the stack,
we'll create a new (larger) array and copy over
the elements
• This will happen infrequently, and the user of the
stack need not worry about it happening
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 42
Implementing Stacks with an Array
• By convention, collection class names indicate
the underlying structure
– So ours will be called ArrayStack
– java.util.Stack is an exception to this
convention
• Our solution will keep the bottom of the stack
fixed at index 0 of the array
• A separate integer called top will indicate where
the top of the stack is, as well as how many
elements are in the stack currently
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 43
Implementing a Stack with an Array
• A stack with elements A, B, C, and D pushed on in
that order:
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 44
package jsjf;
import jsjf.exceptions.*;
import java.util.Arrays;
/**
* An array implementation of a stack in which the
* bottom of the stack is fixed at index 0.
*
* @author Java Foundations
* @version 4.0
*/
public class ArrayStack<T> implements StackADT<T>
{
private final static int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 45
/**
* Creates an empty stack using the default capacity.
*/
public ArrayStack()
{
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty stack using the specified capacity.
* @param initialCapacity the initial size of the array
*/
public ArrayStack(int initialCapacity)
{
top = 0;
stack = (T[])(new Object[initialCapacity]);
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 46
Creating an Array of a Generic Type
• You cannot instantiate an array of a generic type
directly
• Instead, create an array of Object references
and cast them to the generic type
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 47
/**
* Adds the specified element to the top of this stack, expanding
* the capacity of the array if necessary.
* @param element generic element to be pushed onto stack
*/
public void push(T element)
{
if (size() == stack.length)
expandCapacity();
stack[top] = element;
top++;
}
/**
* Creates a new array to store the contents of this stack with
* twice the capacity of the old one.
*/
private void expandCapacity()
{
stack = Arrays.copyOf(stack, stack.length * 2);
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 48
/**
* Removes the element at the top of this stack and returns a
* reference to it.
* @return element removed from top of stack
* @throws EmptyCollectionException if stack is empty
*/
public T pop() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
top--;
T result = stack[top];
stack[top] = null;
return result;
}
/**
* Returns a reference to the element at the top of this stack.
* The element is not removed from the stack.
* @return element on top of stack
* @throws EmptyCollectionException if stack is empty
*/
public T peek() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
return stack[top-1];
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 49
Pushing and Popping a Stack
• After pushing element E:
• After popping:
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 50
Defining an Exception
• An EmptyCollectionException is thrown
when a pop or a peek is attempted and the stack
is empty
• The EmptyCollectionException is
defined to extend RuntimeException
• By passing a string into its constructor, this
exception can be used for other collections as
well
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 51
package jsjf.exceptions;
/**
* Represents the situation in which a collection is empty.
*
* @author Java Foundations
* @version 4.0
*/
public class EmptyCollectionException extends RuntimeException
{
/**
* Sets up this exception with an appropriate message.
* @param collection the name of the collection
*/
public EmptyCollectionException(String collection)
{
super("The " + collection + " is empty.");
}
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 52
Javadoc
• The documentation style used in the postfix
example is called Javadoc
• Javadoc comments are written in a format that
allow a tool to parse the comments and extract
key information
• A Javadoc tool is used to create online
documentation in HTML about a set of classes
• The Java API documentation is generated in this
way
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 53
Javadoc
• Javadoc comments begin with /** and end with
*/
• Specific Javadoc tags, which begin with a @, are
used to identify particular information
• Examples of Javadoc tags:
– @author
– @version
– @param
– @return
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 54
Javadoc
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 55
Testing
Kinds of Testing
• Software systems are tested to ensure the quality of the software
system before delivery to the customer.
• There are many proven methods of testing to achieve this goal
including: Unit tests, functional tests, systems tests, regression tests,
integration tests and acceptance tests.
• For more listings and definitions, visit
http://www.buzzle.com/articles/types-of-software-testing.html
• This can be a huge undertaking and so the use of tools to help
automate any part of the process is worthwhile.
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 56
Unit Testing with JUnit
• In this course, we will be introduced to a tool called Junit that, as its
name implies, provides a framework for automating Unit Testing, which
is a type of testing used to verify that units of code such as classes in
Java work correctly.
• JUnit was designed by Erich Gamma and Kent Beck, the creator of
extreme programming, test driven development. (http://www.junit.org)
It is the de facto standard for Java unit testing.
• Unit Testing is not the only testing strategy to be used when testing a
software system as it only tests the functionality of the units
themselves. It is an important part of the testing practice.
• Unit testing doesn’t uncover errors that occur at the integration level or
system-level errors. So, it is not used to the exclusion of other testing
strategies.
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 57
Junit – White box testing
• White box testing takes an internal perspective of the application and designs
tests based on the internal structure, the code. As such, JUnit is a type of white
box testing.
• JUnit test cases are Java classes that contain one or more unit test methods,
and these tests are grouped into test suites. You can run tests individually, or
you can run entire test suites.
• JUnit works by taking the smallest possible part of testable software (a unit),
isolating this part from the rest of the software and in turn validating that it
works as it is required to work.
• The testing procedure uses verification and validation methods which may
differ from framework to framework but will all essentially test if a specific unit
is fit for use.
• In JUnit the testable units will be the methods within a class and the validation
methods are dependent on the JUnit framework.
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 58
Essential Qualities of a Unit Test
Here are few guidelines to follow when developing a
unit test:
• It must be non-interactive.
• It performs a test by comparing a computed result
with an expected result returning true or false
according to the outcome.
• Each test is independent other tests.
• Each test can be run stand-alone.
• Each test is self-describing.
• The tests are developed before the code that they
test is written.
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 59
Big Picture
• In general, if you want to use Junit to test a class named MyClass:
1.
Create a Junit Test class
– This will import the relevant classes from the JUnit library and be compiled
with the JUnit framework.
2.
3.
Write the test methods.
Use JUnit tool runner to run the class and check for errors.
– The tool runner will check if a unit fails or passes the test, output the
results of the test showing how and where(line number) a test has failed.
4.
5.
Return to the class and correct errors as appropriate.
Run with tool runner again and repeat until all tests are successful.
• Junit Home – http://www.junit.org
• JUnit Starters Guide - http://junit.sourceforge.net/
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 60
Example
•
•
•
•
•
•
•
The following assumes that you are using Junit within the Eclipse IDE. Note that you can download Junit as a jar file and
use it from the command line as well.
To Create a JUnit Tester for MyClass:
Select MyClass in the PackageExplorer, and right-click.
Select New> JUnit Test Case.
Enter a name for the Tester program, such as TestMyClass.
–
•
•
•
•
•
•
•
•
•
•
•
•
•
•
You will see a dialog box with check boxes available to indicate to Junitany additional method stubs to add to the tester program. Select
those as appropriate and then click finish.
You will see that a file named TestMyClass has been added to your project by JUnit.
Select the file in the Package Explorer, and select Run As > JUnit Test.
In the Junit view tab, you will see that the tests have failed for now because none of them have been implemented.
Choose one of the test methods and implement it.
When complete, select the file in the Package Explorer, and select Run As > JUnit Test.
Now the JUnit view displays green highlights for the tests that have succeeded and red for those that have failed with
corresponding error messages.
Continue in like fashion until all tests run successfully.
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 61
Developing the unit tests
• Before you begin, determine what tests need to be run. For example, if testing
a queue class, these might include:
• Test to verify that the queue is empty on construction
• Test to verify that the queue has size 0 on construction
• Test to verify that after n enqueues to an empty queue, n > 0, the queue is not
empty and its size is n
• Test to verify that if we enqueue x then a call to dequeue will result in x
• Test to verify the if we enqueue x then peek will return x
• Test to verify that if the size is n, then after n dequeues, the queue is empty
and has a size 0.
• Test to verify that if the values 1 to 10 are enqueued into an empty queue,
then 10 dequeues will result in an empty queue with size 0 and that the order
of the values dequeued are 1 to 10 in that order.
• Test to verify that dequeueing from an empty queue does throw a
NoSuchElementException.
• Test to verify that peeking into an empty queue does throw a
NoSuchElementException.
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 62
JUnit Test Methods
• Then use the core methods of the Assert class to
develop a test method for each case. See tables
from:
http://www.vogella.com/tutorials/JUnit/article.ht
ml
or
• http://junit.org/javadoc/latest/index.html
12 - 63
Example unit tests
@Test
public void testNewQueueIsEmpty() {
assertTrue(q.isEmpty());
assertEquals(q.size(), 0);
}
@Test
public void testEnqueueThenPeek() {
String message = "Ole Miss";
q.enqueue(message);
int size = q.size();
assertEquals(q.peek(), message);
assertEquals(q.size(), size);
}
@Test
public void testInsertsToEmptyQueue() {
int numberOfInserts = 6;
for (int i = 0; i < numberOfInserts; i++) {
q.enqueue("abc");
}
assertTrue(!q.isEmpty());
assertEquals(q.size(), numberOfInserts);
}
@Test(expected=NoSuchElementException.class)
public void testRemoveOnEmptyQueue() {
assertTrue(q.isEmpty());
q.dequeue();
}
@Test
public void testEnqueueThenDequeue() {
String message = "hello";
q.enqueue(message);
assertEquals(q.dequeue(), message);
@Test(expected=NoSuchElementException.class)
public void testPeekIntoEmptyQueue() {
assertTrue(q.isEmpty());
q.dequeue();
}
}
12 - 64
JUnit annotations - JUnit 4.x uses annotations to mark methods
and to configure the test run.
The following table gives an overview of the most important available
annotations.
From Lars Vogel @
http://www.vogella.com/tutorials/JUnit/article.html
12 - 65
Annotation
@Test
public void method()
Description
The @Test annotation identifies a method as a test method.
@Test (expected =
Exception.class)
Fails if the method does not throw the named exception.
@Test(timeout=100)
Fails if the method takes longer than 100 milliseconds.
@Before
public void method()
This method is executed before each test. It is used to prepare the test environment (e.g., read input data,
initialize the class).
@After
public void method()
This method is executed after each test. It is used to cleanup the test environment (e.g., delete temporary data,
restore defaults). It can also save memory by cleaning up expensive memory structures.
@BeforeClass
public static void method()
This method is executed once, before the start of all tests. It is used to perform time intensive activities, for
example, to connect to a database. Methods marked with this annotation need to be defined as static to work
with JUnit.
@AfterClass
public static void method()
This method is executed once, after all tests have been finished. It is used to perform clean-up activities, for
example, to disconnect from a database. Methods annotated with this annotation need to be defined as static to
work with JUnit.
@Ignore
Ignores the test method. This is useful when the underlying code has been changed and the test case has not yet
been adapted. Or if the execution time of this test is too long to be included.
12 - 66
Assertions
• Assertions -JUnit provides static methods in
the Assert class to test for certain conditions.
These assertion methods typically start
withassert and allow you to specify the error
message, the expected and the actual result.
An assertion method compares the actual value
returned by a test to the expected value, and throws
an AssertionException if the comparison test fails.
• The following table gives an overview of these
methods. Parameters in [] brackets are optional.
• From Lars Vogel @
http://www.vogella.com/tutorials/JUnit/article.html
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
12 - 67
Statement
Description
fail(String)
Let the method fail. Might be used to check that a certain part of the
code is not reached or to have a failing test before the test code is
implemented. The String parameter is optional.
assertTrue([message], boolean condition)
Checks that the boolean condition is true.
assertFalse([message], boolean condition)
Checks that the boolean condition is false.
assertEquals([String message], expected, actual)
Tests that two values are the same. Note: for arrays the reference is
checked not the content of the arrays.
assertEquals([String message], expected, actual, tolerance)
Test that float or double values match. The tolerance is the number of
decimals which must be the same.
assertNull([message], object)
Checks that the object is null.
assertNotNull([message], object)
Checks that the object is not null.
assertSame([String], expected, actual)
Checks that both variables refer to the same object.
assertNotSame([String], expected, actual)
Checks that both variables refer to different objects.
From Lars Vogel @ http://www.vogella.com/tutorials/JUnit/article.html
12 - 68