1 创建计算和字符串连接类
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.junit;
/**
*
* @author Huo
*/
public class Calculator {
public int add(int a,int b){
return a+b;
}
public int minus(int a,int b){
return a-b;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.junit;
/**
*
* @author Huo
*/
public class LinkeString {
public String getlinkeString(String str1,String str2){
String str="";
str=str1+str2;
return str;
}
}
2 创建相应的测试类
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.junit;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Huo
*/
public class CalculatorTest {
/**
* Test of add method, of class Calculator.
*/
@Test
public void testAdd() {
System.out.println("start add...");
int a = 10;
int b = 20;
Calculator instance = new Calculator();
int expResult = 30;
int result = instance.add(a, b);
assertEquals(expResult, result);
}
/**
* Test of minus method, of class Calculator.
*/
@Test
public void testMinus() {
System.out.println("minus");
int a = 30;
int b = 20;
Calculator instance = new Calculator();
int expResult = 10;
int result = instance.minus(a, b);
assertEquals(expResult, result);
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.junit;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Huo
*/
public class LinkeStringTest {
/**
* Test of getlinkeString method, of class LinkeString.
*/
@Test
public void testGetlinkeString() {
System.out.println("getlinkeString");
String str1 = "hello";
String str2 = "world";
LinkeString instance = new LinkeString();
String expResult = "helloworld";
String result = instance.getlinkeString(str1, str2);
assertEquals(expResult, result);
}
}
3 建立suite 类,目的是把所有的测试用例都运行一遍
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.junit;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
*
* @author Huo
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({CalculatorTest.class,LinkeStringTest.class})
public class TestAll {}
4 总结
1 首先通过类的单元测试。
2 把所有的方法集合到一起进行测试。
以上称为单元自动化测试