Writing JUnit
- Any class can have multiple methods having test methods
- A Test method is written using annotation @Test
- Inside test method, use method Assert.assertTrue or Assert.assertEquals to check some conditions
- It takes 2 arguments
- Label to display
- Condition to check
- You can use multiple assertTrue methods in a test method
- Here, if one condition fails, entire test will fail.
Example
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class Sample {
public int square(int num) {
return num * num;
}
@Test
public void TestMyFunction() {
Sample sample = new Sample();
assertTrue("Check 5 ", sample.square(5) == 25);
assertTrue("Check 7 ", sample.square(7) == 49);
...
assertEquals("Check 4 ", sample.square(4), 16);
...
}
@Test
public void TestResult() {
...
...
}}
Run JUnit
- In eclipse, right click on class
- Click Run as... > Run configuration... , Choose the test and Click Run
OR
Click Run as... > JUnit test , It runs all the tests by default.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.