当一个项目中存在较多case需要测试时,我们可以利用JUnit提供的Suite来测试。
步骤如下:
1.首先我们编写两个被测试的java文件,如下:
package com.jc.demo1;
public class Demo1 {
public int add(int a,int b){
return a+b;
}
public int minus(int a,int b){
return a-b;
}
}
package com.jc.demo1;
public class Demo2 {
public int divide(int a,int b){
return a/b;
}
public int mul(int a,int b){
return a*b;
}
}
2.分别编写两个test case,如下:
package com.jc.demo1;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestDemo1 {
Demo1 demo1;
@Before
public void setUp() throws Exception {
demo1=new Demo1();
}
@After
public void tearDown() throws Exception {
}
@Test
public void testAdd() {
int rel=demo1.add(12, 22);
assertEquals("加法有问题",rel,34);
}
@Test
public void testMinus() {
int rel=demo1.minus(24, 12);
assertEquals("减法有问题",rel,12);
}
}
package com.jc.demo1;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestDemo2 {
Demo2 demo2;
@Before
public void setUp() throws Exception {
demo2=new Demo2();
}
@After
public void tearDown() throws Exception {
}
@Test
public void testDivide() {
int rel=demo2.divide(24, 12);
assertEquals("除法有问题",rel,2);
}
@Test
public void testMul() {
int rel=demo2.mul(2, 12);
assertEquals("乘法有问题",rel,24);
}
}
目前有两种方法可以
方法一:
package com.jc.demo1;
import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import junit.framework.TestSuite;
public class SuiteTest2 {
public static Test suite(){
TestSuite suite= new TestSuite(SuiteTest2.class.getName());
suite.addTest(new JUnit4TestAdapter(TestDemo1.class));
suite.addTest(new JUnit4TestAdapter(TestDemo2.class));
return suite;
}
}
方法二
package com.jc.demo1;
import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import junit.framework.TestSuite;
public class SuiteTest2 {
public static Test suite(){
TestSuite suite= new TestSuite(SuiteTest2.class.getName());
suite.addTest(new JUnit4TestAdapter(TestDemo1.class));
suite.addTest(new JUnit4TestAdapter(TestDemo2.class));
return suite;
}
}