您的位置:首页 > 编程语言 > Java开发

在MyEclipse 2014 中使用JUnit-(二)

2016-01-14 10:50 549 查看
当一个项目中存在较多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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: