Java Reference
In-Depth Information
public void testStack() {
// first we set up the object(s) to be tested
Stack aStack # new Stack();
// we check if a condition (at creation the stack should
// be empty) is met. If not an error message is shown
assertTrue("Stack should be empty at creation",
aStack.isEmpty());
// we perform some operations
aStack.push(10);
aStack.push(-4);
// we check some conditions are met
assertEquals(-4,aStack.pop());
assertEquals(10,aStack.pop());
}
}
}
The assert methods are public methods that are inherited from the TestCase
class. These methods start with “assert” and can be used in the test methods.
The simplest assert method is assertTrue whose syntax is: assertTrue(“ message”,
condition) . If the condition is false the test fails, the message is printed, and the
rest of the test method is skipped. Otherwise the assertion is considered passed
and the test methods proceed.
For instance:
assertTrue("Stack should be empty at creation",
// error message
aStack.isEmpty()); // condition to check
For integers, longs, bytes, chars and objects it is possible to use assertEquals
whose syntax is: assertEquals(expectedValue, actualValue) . For floating point values
a variation of this method can be used, the syntax is: assertEquals(expectedValue,
actualValue, error) . If the comparison is successful the test methods proceed,
otherwise the assert fails and the remaining test methods are skipped.
assertEquals(-4,aStack.pop());
assertEquals(1.0, Math.cos(3.14), 0.01);
For each test case JUnit executes all of its public test methods and ignores all
the rest. If all the assert statements (invocations to assert methods) in a test
method have success the test is considered passed, otherwise if only one assert
statement fails the test fails.
Usually a test case class contains, in addition to the test methods, a set of helper
methods that are either private or have names not starting with “test”. These
methods are used to factorize pieces of code that are common to several test
methods.
3.5
Prototype 2: User interaction
The second prototype implements a graphical user interface (GUI) that
supports sophisticated patterns of interaction between the user and the
 
Search WWH ::




Custom Search