"JUnit" is a framework for Java unit testing. You can verify that it works correctly by writing a unit test.
--If the class name to be tested is "Xxx", the test class name will be "XxxTest". --If the method name to be tested is "Yyy", the test method name will be "testYyy". --Add annotation "@Test" to the test method. Make it "public void" --The test method is "assertThat (actual value, is (expected value));" --Write code that makes "prerequisites, execution, verification" easy to understand
The basic usage is as follows.
Sample.java
public class Sample {
public static int toDouble(int num) {
return num * 2;
}
}
Here's a JUnit test for the sample above:
SampleTest.java
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class SampleTest {
@Test
public void testToDouble() {
int actual = Sample.toDouble(10);
int expect = 20;
assertThat(actual, is(expect));
}
}
If it does not return the expected value, the test will fail as follows:
java.lang.AssertionError:
Expected: is <21>
but: was <20>
You can temporarily ignore the test by giving @Ignore.
@Ignore @Test
public void doSomething() { /* ... */ }
Recommended Posts