Java Reference
In-Depth Information
Table 13.1 JUnit Naming
In your original code
In your test case
Class
MyClass
MyClassTest
Method
myMethod
testMyMethod
prepend the word “test” to the method name, and capitalize the now-no-longer-
first letter. Again, JUnit will use this naming convention, along with
introspection, to automatically derive the test names from the actual method
names (more on that later, too). The naming conventions we've seen so far are
summarized in Table 13.1.
Let's take a quick look at the code. We import the framework for JUnit
test cases, so that the compiler can resolve the names that deal with JUnit stuff.
The TestCase class that we extend is part of that JUnit stuff. It's an abstract
class that defines much of what we use for testing. We just fill in what we need.
The TestCase class defines a method called setUp() . The setUp()
method is called not just once, but before every test method is called. That way
you can initialize variables and get into a known state before each test. Since
it's already defined in the TestCase class, we can override it (as in our example)
to do what we want, or we can not include it in our class and get the default
behavior from TestCase (which is to do nothing).
There is also a method named tearDown() which you can override if you
need to close things up at the end of a test case (e.g., close a database connec-
tion). As with setUp() , its default behavior, as defined in TestCase , is to do
nothing.
The test case itself—the method where we will exercise our class—is called
testCreateSub (since we want to test our createSub() method). Inside such
a method (and we could have more than one) we write code which uses the
objects in our application. Then at various junctures in the code we make asser-
tions about the state of things—for example, this variable should be non-null,
or this expression should have this particular value.
Those assertions are, to our way of thinking, the tests. We're testing to see
if the subaccount was created, or if the main account did, indeed, use up all of
its dollars in allocation to the subaccounts. But they are not what is called tests
by JUnit. Rather, each individual method in a test class is considered a single
test. Such test methods are, typically, a collection of assertions surrounding the
use of a single (application) method. So in our example, the method
Search WWH ::




Custom Search