环境
- Java 版本:1.8.0_172
- IDEA 版本:ideaIU-2017.3.5
情景代码
/**
* Created by Administrator on 2018/6/16 12:00 in Beijing.
*/
public class Calculator {
public int add(int a, int b) {
return a + b ;
}
public int sub(int a, int b) {
return a - b ;
}
public int mul(int a, int b) {
return a * b ;
}
public int div(int a, int b) {
if(b == 0) {
throw new ArithmeticException("除数不能为零") ;
}
return a / b ;
}
}
使用过程
右键相应的类,Go To --> Test,弹出如下框
点击OK后,IDEA 将自动 帮我们 创建好 测试代码。
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by Administrator on 2018/6/16 21:29 in Beijing.
*/
public class CalculatorTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void add() {
}
@Test
public void sub() {
}
@Test
public void mul() {
}
@Test
public void div() {
}
}
最终的测试代码如下,
import org.junit.*;
import static org.junit.Assert.*;
/**
* Created by Administrator on 2018/6/16 21:29 in Beijing.
*/
public class CalculatorTest {
@BeforeClass
public static void beforeClass() {
System.out.println("Before Class");
}
@AfterClass
public static void afterClass() {
System.out.println("After Class");
}
@Before
public void setUp() throws Exception {
System.out.println("Before Method");
}
@After
public void tearDown() throws Exception {
System.out.println("After Method");
}
@Test
public void add() {
System.out.println("add");
int a = 20 ;
int b = 10 ;
Calculator cal = new Calculator() ;
int result = cal.add(20, 10) ;
Assert.assertEquals(a + b, result) ;
}
@Test
public void sub() {
System.out.println("sub");
int a = 20 ;
int b = 10 ;
Calculator cal = new Calculator() ;
int result = cal.sub(20, 10) ;
Assert.assertEquals(a - b, result) ;
}
@Test
public void mul1() {
System.out.println("mul1");
int a = 20 ;
int b = 10 ;
Calculator cal = new Calculator() ;
int result = cal.mul(20, 10) ;
Assert.assertEquals(a * b, result) ;
}
@Test
@Ignore
public void mul2() {
System.out.println("mul2");
int a = 20 ;
int b = 10 ;
Calculator cal = new Calculator() ;
int result = cal.mul(20, 10) ;
Assert.assertEquals(a * b, result) ;
}
@Test
public void div1() {
System.out.println("div1");
int a = 20 ;
int b = 10 ;
Calculator cal = new Calculator() ;
int result = cal.div(20, 10) ;
Assert.assertEquals(a / b, result) ;
}
@Test(expected = ArithmeticException.class)
public void div2() {
System.out.println("div2");
int a = 20 ;
int b = 0 ;
Calculator cal = new Calculator() ;
int result = cal.div(20, 10) ;
Assert.assertEquals(a / b, result) ;
}
}
最后点击Run方法,
输出如下,
大功告成。