The JUnit library implements several resources for you to use in testing your programs. In this experiment you will pick up the basics of using JUnit.
Do this...
Create a test-case class named
Experiment01Test
.
Everything in Java revolves around classes. Previously, you've seen classes used to implement drivers. For this lab you will create test-case classes. This first experiment will demonstrate what you can (and should) do in a test case class.
Do this...
Run your test-case class.
Keep in mind that this is a test-case class, not a driver---this distinction is very important for running the class properly.
You'll get some output that says that something is wrong: you don't have any actual tests!
This is what it looks like for me in Eclipse:
It will look slightly different in other IDEs and in JUnit's own test runner. However, the basic features are the same.
The failure trace here indicates that there are no tests that are found in the class.
A test-case class needs to be filled with test methods. "Method" is a technical term in Java which we'll explore in better detail in the next lab; for now, it's just a place to put some testing assertions. Every test method needs to follow this pattern:
test-method pattern |
public void test
|
So add a test method to Experiments
.
Do this...
Add this code inside the Experiment01Test
class (i.e., before the very last curly brace):
public void testSimpleAssertions() { }
The name of the test method (e.g.,
testSimpleAssertions
) should indicate what you're
trying to test in the test method.
Again (and this is the last time you'll be reminded), you're running a test-case class, not a driver!
JUnit will now show you a green bar because your one test passes. Of course, it works because nothing is actually being tested! Actual tests are made with assertions.
Do this...
Add this code inside the curly braces of
testSimpleAssertions()
:
assertEquals("A simple test that 2 equals 2", 2, 2);
This appears to test (i.e., to assert) that 2 equals 2. That's exactly what it does:
assertion-statement pattern |
assertEquals(
|
You're testing something, and apparently it's working fine. Or is it? Try getting something to fail, like this:
Do this...
Add this assertion statement after the one you just added:
assertEquals("A test that fails", 2, 3);
Question #03.01.01 Describe how you can tell
that this new assertion statement failed. That is, how does JUnit
make it clear that something went wrong?
To be answered in Exercise
Questions/lab03.txt
.
Do this...
Comment out the assert statement that fails, and then compile, and run the test-case class so that the
tester passes its one test.
%% TODO: too Eclipse specific You now have three places to look for problems.
Now try an assertion of your own.
Do this...
Add another assertion statement to assert that 1234 is equal to
1234.
assert, assertion, driver, test-case class, test method