ProjectA ---- src
|
------ xx.yy.zzz(package)
|
------- Door.java (Tested class)
Create a class "DoorTest.java" for testing Door.java (test target class) under package xx.yy.zzz.
DoorTest.java
package xx.yy.zzz; //Make it the same package as the class under test
import static org.junit.Assert.*;
import org.junit.Test;
public class DoorTest {
@Test
public void test() {
fail("Not yet implemented");
}
}
Set the required value referring to the figure below. Don't forget to use "JUnit 4" as the test runner!
Execution result. The result is always "fail" because the fail method is called.
Door.java
package xx.yy.zzz; //Make it the same package as the test class
public class Door {
private boolean isOpen = false;
public void open(String str) {
if (str.equals("open Sesame!")) {
isOpen = true;
} else {
isOpen = false;
System.out.println("wrong.");
}
}
public void close() {
isOpen = false;
}
// getter
public boolean isOpen() {
return isOpen;
}
}
Door.java
package xx.yy.zzz; //Make it the same package as the class under test
import static org.junit.Assert.*;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class DoorTest {
Door door;
private ByteArrayOutputStream baos;
//Preprocessing
@Before
public void setUp() {
door = new Door();
baos = new ByteArrayOutputStream();
System.setOut(
new PrintStream(
new BufferedOutputStream(baos)
)
);
}
// 「@"Test" is an annotation for JUnit to recognize as a test method.
//Create with public void
@Test
public void test1() {
door.open("Please open the door");
//Standard output
System.out.flush();
String expected = "wrong.\r\n";
String actual = baos.toString();
//Confirmation with expected value
assertEquals(false, door.isOpen());
assertEquals(expected, actual);
}
@Test
public void test2() {
door.open("open Sesame!");
assertEquals(true, door.isOpen());
}
@Test
public void test3() {
door.close();
assertEquals(false, door.isOpen());
}
//Post-processing
@After
public void fin() {
// DO Nothing
}
}
[Supplement]
Recommended Posts