IDEA中使用JUnit4教程 超详细!(单元测试框架)
导语:自动化测试的必经之路–Selenium
作者:变优秀的小白
Github:YX-XiaoBai
交流群(new):
爱好:Americano More Ice !
话不多说,实战为主!
注:如中途遇到不懂的地方,直接评论留言看到会马上答疑!
首先我们要认识什么是JUnit
public class Calculator { public int result=0; public int add(int operand1,int operand2){ result=operand1+operand2; //将两个传入参数进行相加操作 return result; } public int subtract(int operand1,int operand2){ result=operand1-operand2; //将两个传入参数进行相减操作 return result; } public int multipe(int operand1,int operand2){ result=operand1*operand2; //将两个传入参数进行相乘操作 for(;;){ //死循环 } } public int divide(int operand1,int operand2){ result=operand1/0; //除0操作 return result; } public int getResult(){ return this.result; //返回计算结果 } }
7.创建Junit4的测试代码,有两种方法(超级简单方便),第一种直接点击被测试类Calculator 使用 Ctrl+Shift+T

第二种方法 鼠标右键点击类名 使用 goto-Test(本人使用IDEA下错成汉化版表示难受)即可实现

8.创建测试,根据自身需要来勾选

我把测试类代码直接给出来,可根据需要自行修改
import org.junit.*; import static org.junit.Assert.*; public class CalculatorTest { private static Calculator cal=new Calculator(); @BeforeClass public static void setUpBeforeClass() throws Exception{ System.out.println("@BeforeClass"); } @AfterClass public static void tearDownAfterClass() throws Exception{ System.out.println("@AfterClass"); } @Before public void setUp() throws Exception { System.out.println("测试开始"); } @After public void tearDown() throws Exception { System.out.println("测试结束"); } @Test public void testAdd() { cal.add(2,2); assertEquals(4,cal.getResult()); //fail("Not yet implemented"); } @Test public void testSubtract() { cal.subtract(4,2); assertEquals(2,cal.getResult()); //fail("Not yet implemented"); } @Ignore public void testMultiply() { fail("Not yet implemented"); } @Test(timeout = 2000) public void testDivide() { for(;;); } @Test(expected = ArithmeticException.class) public void testDivideByZero(){ cal.divide(4,0); } }
org.seleniumhq.selenium
selenium-java
3.14.0
junit
junit
4.12
test
org.jboss.shrinkwrap
shrinkwrap-api
1.2.6
org.jboss.arquillian.junit
arquillian-junit-container
1.4.1.Final
test
此时一个简单的Junit注解使用就算成功了!
最后附上一些使用到的概念:
一个测试类中只能声明此注解一次,此注解对应的方法只能被执行一次
@BeforeClass 使用此注解的方法在测试类被调用之前执行
@AfterClass 使用此注解的方法在测试类被调用结束退出之前执行
一个类中有多少个@Test注解方法,以下对应注解方法就被调用多少次
@Before 在每个@Test调用之前执行
@After 在每个@Test调用之后执行
@Test 使用此注解的方法为一个单元测试用例,一个测试类中可多次声明,每个注解为@Test只执行一次
@Ignore 暂不执行的测试用例,会被JUnit4忽略执行
总结: 大家如果有什么疑问或者建议的地方,可直接留言评论!本人会一一回复!!
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/217523.html原文链接:https://javaforall.net
