Java Reference
In-Depth Information
Test cases and test methods
All JU nit tests stem from the base class junit.framework.TestCase . To create your
own test case, you extend this class. There are no required methods to imple-
ment, and there is no need to modify your existing code. What could be simpler?
However, in order to test something, you must create at least one test method to
exercise a portion of your code. Any test case can contain as many test methods as
you require. Test methods should be fine grained, testing a single operation criti-
cal to the correct operation of your code. They should also be standalone and not
require any special setup or be expected to run in any particular order. Not only
does this make them easy to write, it also makes them easy to use. All that is
required by the framework is that your test methods begin with the name test
and adhere to the following method signature:
public void testSomething()
Test methods can also declare exceptions.
Beyond starting with the word test , it doesn't matter what you call your test, but
you should probably name it something meaningful to help indicate its purpose—
this name is used as a label when running and reporting on the results of the test.
You're free to add other methods to the test class as needed to assist in testing.
How JUnit runs your tests
The reason for the naming restriction is that JU nit relies on Java's reflection mecha-
nism to locate and run the individual test methods. When passed into an applica-
tion that knows how to run JU nit tests (like IDEA ), the test case's test methods can
be determined on the fly. This means all you have to do to write new tests is create
new methods and add them to a test case. No configuration files, no changes to your
source code, no flaming hoops to jump through. You may notice that the test
method doesn't return a boolean as you might expect. So how does a test pass? A
test passes as long as it doesn't fail. And failing tests is the job of assertions .
Assertions
If you're familiar with JDK 1.4's assert keyword, be advised that it isn't used in the
JU nit framework, but the concept is similar. Like the assert keyword, JU nit's
assertion methods are designed to evaluate boolean pass/fail conditions. For
example, a method may verify that a variable has a certain value, a list isn't empty,
or that two objects that should be equivalent really are.
If any assertion fails, the test fails with a failure , an expected or tested-for
condition; if any uncaught exception is thrown, the test fails with an error, an
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search