Junit 4.x 单元测试,参数化测试,套件测试 实例

对下面三个类进行单元测试 ,组成套件测试。

public class Calculate {
public int add(int a, int b) {
return a + b;
} public int sub(int a, int b) {
return a - b;
}
}
public class Car {
public int getWheels() {
return 4;
}
}
public class  Rectangle{
public int getArea(int width,int height){
return width*height;
}
}

测试代码:建议把测试代码放在test源文件中

public class CalculateTest {
Calculate calculate; @Before
public void setUp() throws Exception {
calculate = new Calculate();
} @Test
public void testAdd() {
int result = calculate.add(12, 12);
assertEquals(24, result);
} @Test
public void testSub() {
int result = calculate.sub(12, 12);
assertEquals(0, result);
} }
public class CarTest {
Car car; @Before
public void setUp() throws Exception {
car = new Car();
} @Test
public void testGetWheels() {
int result = car.getWheels();
assertEquals(4, result);
} }
public class RectangleTest {
Rectangle rectangle;
@Before
public void setUp() throws Exception {
rectangle=new Rectangle();
} @Test
public void testGetArea() {
int result = rectangle.getArea(12, 2);
assertEquals(24, result);
}
}

测试套件代码:

@RunWith(Suite.class)
@SuiteClasses({ CalculateTest.class, CarTest.class, RectangleTest.class })
public class AllTests { }

请用下面的参数对Calculate类的add方法进行参数化的测试

{2,1,1},

{2,0,2},

{0,2,-2},

@RunWith(Parameterized.class)
public class CalculateTest2 {
Calculate calculate;
private int input1;
private int input2;
private int expected;
@Parameters
public static Collection prepareData() {
Object[][] object = { { -1, -2, -3 }, { 0, 2, 2 }, { -1, 1, 0 },
{ 1, 2, 3 } };
return Arrays.asList(object);
} public CalculateTest2(int input1, int input2, int expected) {
this.input1 = input1;
this.input2 = input2;
this.expected = expected;
} @Before
public void setUp() throws Exception {
calculate = new Calculate();
} @Test
public void testAdd() {
int result = calculate.add(input1, input2);
assertEquals(expected, result);
}
}
上一篇:testng多线程并行执行测试


下一篇:JUnit套件测试实例