The first chapter exercises is to create a chess pawn Pawn class.
1, create PawnTest empty test class, try to run the JUnit, the result can not be run. Because I am using JUnit4, in the JUnit4 test classes and regular classes are the same, when you give him a way coupled with annotation "@ Test", identify this is a test; and did not like the previous version must be TestCase sub-class, and use a special naming method to identify test methods.
public class PawnTest {
} 2, create a test method TestCreate. Now you can run JUnit. And you can see the green of JUnit.
@Test
public void testCreate() {
} 3, in the testCreate add a Pawn object code.
@Test
public void testCreate() {
Pawn pawn = new Pawn();
} Obviously, this will lead to compilation error, an error is not a problem, as long as we are the solution promptly lost him. So we create a Pawn class.
public class Pawn {
} Now there is no compile error. And run JUnit you can see the green roads lead to. All normal, the next step.
4, adding a claim to determine whether we have the new default white pawn (the default default soldier is white).
@Test
public void testCreate() {
Pawn pawn = new Pawn();
assertEquals("white", pawn.getColor());
} Created in the Pawn method getColor, to ensure the normal compile:
public String getColor() {
return null;
} Run JUnit, red stripe! ! Failures: 1.JUnit tells us that there is a failed test would have to be "white", but it is "null", we have to face up to mistakes, the most simple way to fix it. So we getColor returns "white".
public String getColor() {
return "white";
} Run JUnit, green reproduce article. To normal the next step.
5, in the testCase add a black soldier:
Pawn blackPawn = new Pawn("black");
assertEquals("black", blackPawn.getColor()); In order to solve the compilation error, in the Pawn to add two constructors:
public Pawn() {
}
public Pawn(String color) {
} Compile issue is resolved, run JUnit. Red stripe! ! Failures: 1, deal with it. Because my getColor direct return "white", you must modify the allowed return the correct color. Modifications of the Pawn class are as follows:
private String color;
public Pawn() {
this.color = "white";
}
public Pawn(String color) {
this.color = color;
}
public String getColor() {
return this.color;
} Run JUnit, see the green section, the next step.
6, reconstruction, the program is defined as a constant in the string. The PawnTest inside add:
final String white = "white";
final String black = "black";
Inside the Pawn add:
static final String defaultColor = "white";and the proceedings which directly modify the string for this hand-written a few constants.
The final program in this chapter in the annex inside. My environment: windows, eclipse3.5, jdk1.6, JUnit4.5







