个人感觉看谁的都不如直接看官网的教程,简单、可靠
JUnit4官网教程 :点击打开链接
使用Eclipse 建立一个Java 功能,并导入一下两个JAR包(可从官网上下载两个JAR包, 注:网络连接可能存在问题,可将http连接改为https即可):
本教程功能
(1) JUnit4的基本使用方法,
(2) 多个测试类一起执行的方法,Suites.class
(3)一次性测试多个测试用例的情况,Parameters
工程的目录
代码说明:
Caculator.java:计算类,方法包括add, sub, multiply
Caculator2.java:计算类,方法包括divide
CaculatorTest.java, Caculator2Test.java:测试类
suitTest.java:打包测试类
详细代码
Caculator.java
package com.junit.Test; public class Caculator { public int add(int a, int b){ return a + b; } public int sub(int a, int b){ return a - b; } public int multiply(int a, int b){ return a * b; } }
Caculator2.java
package com.junit.Test; public class Caculator2 { public int divide(int a, int b){ return a / b; } }
CaculatorTest.java
<strong><span style="font-size:12px;">package com.junit.Test; import static org.junit.Assert.*; import org.junit.Test; public class CaculatorTest { private static Caculator cal = new Caculator(); @Test public void testAdd() { assertEquals(3, cal.add(1, 2)); } @Test public void testSub() { assertEquals(0, cal.sub(2, 2)); } @Test(timeout=1000) public void testMultiply(){ assertEquals(3, cal.multiply(1, 3)); } } </span></strong>
Caculator2Test.java
<strong><span style="font-size:12px;">package com.junit.Test; import static org.junit.Assert.*; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class Caculator2Test { private static Caculator2 cal2 = new Caculator2(); @Parameter(value = 0) public int inputa; @Parameter(value = 1) public int inputb; @Parameter(value = 2) public int expected; @Parameters public static Collection<Object[]> data(){ return Arrays.asList(new Object[][]{ {2,1,2},{6,3,2} }); } @Test public void testDivide() { assertEquals(expected, cal2.divide(inputa, inputb)); } } </span></strong>
suitTest.java
package com.junit.Test; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ CaculatorTest.class, Caculator2Test.class }) public class suitTest { @Test public void test() { fail("Not yet implemented"); } }
测试
选中项进行测试的测试类,suitTest测试类将执行两个测试类一起执行
Run as ->Junit Test
结果
执行suitTest类的结果如下:
时间: 2024-10-21 08:36:29