Download JUnit: Writing and Running Tests with Java and more Slides Computer Science in PDF only on Docsity!
JUnit
Test suites
- Obviously you have to test your code to get it working in the
first place
- You can do ad hoc testing (running whatever tests occur to you at the moment), or
- You can build a test suite (a thorough set of tests that can be run at any time)
- Disadvantages of a test suite
- It’s a lot of extra programming
- This is true, but use of a good test framework can help quite a bit
- You don’t have time to do all that extra work
- False --Experiments repeatedly show that test suites reduce debugging time more than the amount spent building the test suite
- Advantages of a test suite
- Reduces total number of bugs in delivered code
- Makes code much more maintainable and refactorable
- This is a huge win for programs that get actual use!
Rhythm
- “There is a rhythm to developing software unit tests first.
You create one test to define some small aspect of the problem
at hand.
Then you create the simplest code that will make that test pass.
Then you create a second test.
Now you add to the code you just created to make this new
test pass, but no more!
Not until you have yet a third test.
You continue until there is nothing left to test.”
http://www.extremeprogramming.org/rules/testfir
st.html
JUnit
• JUnit is a framework for writing tests
- JUnit was written by Erich Gamma (of Design Patterns fame) and Kent Beck (creator of XP methodology)
- JUnit uses Java’s reflection capabilities (Java programs can examine their own code)
- JUnit helps the programmer:
- define and execute tests and test suites
- formalize requirements and clarify architecture
- write and debug code
- integrate code and always be ready to release a working
version
- JUnit is not yet (as far as I know) included in Sun’s SDK, but an increasing number of IDEs include it
- BlueJ, JBuilder, and Eclipse now provide JUnit tools
Structure of a JUnit test class
- Suppose you want to test a class named Fraction
- public class FractionTest
extends junit.framework.TestCase {
- This is the unit test for the Fraction class; it declares (and possibly defines) values used by one or more tests
- public FractionTest() { }
- This is the default constructor
- protected void setUp()
- Creates a test fixture by creating and initializing objects and values
- protected void tearDown()
- Releases any system resources used by the test fixture
- public void testAdd(), public void testToString(), etc.
- These methods contain tests for the Fraction methods add(), toString() , etc. (note how capitalization changes)
Assert methods I
- Within a test,
- Call the method being tested and get the actual result
- assert what the correct result should be with one of the provided assert methods
- These steps can be repeated as many times as necessary
- An assert method is a JUnit method that performs a test, and
throws an AssertionFailedError if the test fails
- JUnit catches these Errors and shows you the result
- static void assertTrue(boolean test )
static void assertTrue(String message , boolean test )
- Throws an AssertionFailedError if the test fails
- The optional message is included in the Error
- static void assertFalse(boolean test )
static void assertFalse(String message , boolean test )
- Throws an AssertionFailedError if the test fails
JUnit tests for Counter
public class CounterTest extends junit.framework.TestCase { Counter counter1;
public CounterTest() { } // default constructor
protected void setUp() { // creates a (simple) test fixture counter1 = new Counter(); }
protected void tearDown() { } // no resources to release
public void testIncrement() { assertTrue(counter1.increment() == 1); assertTrue(counter1.increment() == 2); }
public void testDecrement() { assertTrue(counter1.decrement() == -1); } }
Note that each test begins with a brand new counter
This means you don’t have to worry about the order in which the tests are run
The Counter class itself
public class Counter { int count = 0;
public int increment() { return ++count; }
public int decrement() { return --count; }
public int getCount() { return count; } }
- Is JUnit testing overkill for this little class?
- The Extreme Programming view is: If it isn’t tested, assume it doesn’t work
- You are not likely to have many classes this trivial in a real program, so writing JUnit tests for those few trivial classes is no big deal
- Often even XP programmers don’t bother writing tests for simple getter methods such as getCount()
- We only used assertTrue in this example, but there are additional assert methods
Assert methods III
- assertNull(Object object ) assertNull(String message , Object object ) - Asserts that the object is null
- assertNotNull(Object object ) assertNotNull(String message , Object object ) - Asserts that the object is null
- fail() fail(String message ) - Causes the test to fail and throw an AssertionFailedError - Useful as a result of a complex test, when the other assert methods aren’t quite what you want
The assert statement
- Earlier versions of JUnit had an assert method instead of an
assertTrue method
- The name had to be changed when Java 1.4 introduced the assert statement
- There are two forms of the assert statement:
- assert boolean_condition ;
- assert boolean_condition : error_message ;
- Both forms throw an AssertionFailedError if the boolean_condition is false
- The second form, with an explicit error message, is seldom necessary
- When to use an assert statement:
- Use it to document a condition that you “know” to be true
- Use assert false; in code that you “know” cannot be reached (such as a default case in a switch statement)
- Do not use assert to check whether parameters have legal values, or other places where throwing an Exception is more appropriate
JUnit in BlueJ
BlueJ, go to the
Preferences... and
check Show Unit
Testing Tools
menus in BlueJ
Viewing test results
If you run a single test, and it is successful, you just get a
message in the status line
Failed tests
Unexpected errors and exceptions
First steps toward solutions
• Rather than always printing on System.out, you can
do your printing on an arbitrary PrintStream
- The PrintStream can be passed into methods as a parameter
- Alternatively, you can redefine System.out to use a different PrintStream with System.setOut( PrintStream )
• You can “automate” GUI use by “faking” events
- Here’s a starter method for creating your own events:
- public void fakeAction(Component c) {
getToolkit().getSystemEventQueue().postEvent(
new ActionEvent(c, ActionEvent.ACTION_PERFORMED,
- You can explore the Java API to discover how to create other kinds of events
The End