Adding a Test


Edit the source for your StudentTest class to look like the following code:

 public class StudentTest extends junit.framework.TestCase {    public void testCreate() {    } } 

The new second and third lines define a method within the StudentTest class:

 public void testCreate() { } 

A method is a block of code that will contain any number of code statements. Like the class declaration, Java uses braces to delineate where the method starts and where it ends. All code that appears between method braces belongs to the method.

The method in this example is named testCreate. It is designated as being public, another requirement of the JUnit testing framework.

Methods have two general purposes. First, when Java executes a method, it steps through the code contained within the braces. Among other things, method code can call other methods; it can also modify object attributes. Second, a method can return information to the code that executed it.

The testCreate method returns nothing to the code that invoked itJUnit has no need for such information. A method that returns no information provides what is known as a void return type. Later (see Returning a Value from a Method in this lesson) you will learn how to return information from a method.

The empty pair of parentheses () indicates that testCreate takes no arguments (also known as parameters)it needs no information passed to it in order to do its work.

The name of the method, testCreate, suggests that this is a method to be used for testing. However, to Java, it is just another method name. But for JUnit to recognize a method as a test method, it must meet the following criteria:

  • the method must be declared public,

  • the method must return void (nothing),

  • the name of the method must start with the word test, in lowercase letters, and

  • the method cannot take any arguments ().

Compile this code and rerun JUnit's TestRunner. Figure 1.4 shows that things are looking better.

Figure 1.4. JUnit success (showing a green bar)


The green bar is what you will always be striving for. For the test class StudentTest, JUnit shows a successful execution of one test method (Runs: 1) and no errors or failures.

Remember that there is no code in testCreate. The successful execution of JUnit demonstrates that an empty test method will always pass.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net