Demo directory structure
1. Create a new project (junit4Demo), build a package (com.imooc.util) under src, and create a new Calculate.java in the package
package com.imooc.util;
public class Calculate
{
public int add(int a, int b)
{
return a + b;
}
public int subtract(int a, int b)
{
return a - b;
}
public int multiply(int a, int b)
{
return a * b;
}
public int devide(int a, int b)
{
return a / b;
}
}
2. Import the unit test jar package: right click Build Path --> Add Libraries --> Junit --> Junit4
3. Create a new test class (CalculateTest.java): right-click the package where the test class is located: new --> JUnit Test Case
package com.imooc.util;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CalculateTest
{
@Test
public void add()
{
// assertEquals(预测值, 传参)
assertEquals(6, new Calculate().add(3, 3));
}
}
4. Run the test: CalculateTest right click --> Run as JUnit Test
5. Junit view: status bar (green-test successful; red-test failed)