實戰(zhàn)開發(fā)篇
本節(jié)內容主要介紹JUnit單元測試功能框架,并以實戰(zhàn)演練的形式進行講解。本系列教程主要針對代碼編程方式和模型,重點講解實戰(zhàn)代碼開發(fā)。通過本系列教程的學習,您將能夠深入了解JUnit單元測試框架的使用和原理,并掌握如何在實際項目中運用JUnit進行單元測試。
創(chuàng)建Pojo模型
以下是一個使用JUnit對業(yè)務邏輯類和測試運行器中的測試類進行測試的示例。首先,我們需要創(chuàng)建一個名:EmployeeDetails.java的POJO類。
EmployeeDetails 類被用于
- 取得或者設置雇員的姓名的值。
- 取得或者設置雇員的每月薪水的值。
- 取得或者設置雇員的年齡的值。
public class EmployeeDetails {
private String name;
private double monthlySalary;
private int age;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the monthlySalary
*/
public double getMonthlySalary() {
return monthlySalary;
}
/**
* @param monthlySalary the monthlySalary to set
*/
public void setMonthlySalary(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
}
EmpBusinessLogic 類被用來計算:
- 雇員每年的薪水
- 雇員的評估金額
創(chuàng)建一個名為 EmpBusinessLogic.java 的 business logic 類:
public class EmpBusinessLogic {
// Calculate the yearly salary of employee
public double calculateYearlySalary(EmployeeDetails employeeDetails){
double yearlySalary=0;
yearlySalary = employeeDetails.getMonthlySalary() * 12;
return yearlySalary;
}
// Calculate the appraisal amount of employee
public double calculateAppraisal(EmployeeDetails employeeDetails){
double appraisal=0;
if(employeeDetails.getMonthlySalary() < 10000){
appraisal = 500;
}else{
appraisal = 1000;
}
return appraisal;
}
}
}
創(chuàng)建一個名為 TestEmployeeDetails.java 的準備被測試的測試案例類
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestEmployeeDetails {
EmpBusinessLogic empBusinessLogic =new EmpBusinessLogic();
EmployeeDetails employee = new EmployeeDetails();
//test to check appraisal
@Test
public void testCalculateAppriasal() {
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);
double appraisal= empBusinessLogic.calculateAppraisal(employee);
assertEquals(500, appraisal, 0.0);
}
// test to check yearly salary
@Test
public void testCalculateYearlySalary() {
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);
double salary= empBusinessLogic.calculateYearlySalary(employee);
assertEquals(96000, salary, 0.0);
}
}
創(chuàng)建一個名為 TestRunner.java 的類來執(zhí)行測試案例類:
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestEmployeeDetails.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
斷言操作
所有的斷言都包含在 Assert 類中
public class Assert extends java.lang.Object
該類提供了許多有用的斷言方法,可用于編寫測試用例。僅記錄失敗的斷言。以下是Assert類中一些有用的方法的示例:
序號 | 方法和描述 |
---|---|
1 | void assertEquals(boolean expected, boolean actual) 檢查兩個變量或者等式是否成立 |
2 | void assertTrue(boolean expected, boolean actual) 檢查條件為真) |
3 | void assertFalse(boolean condition) 檢查條件為假 |
4 | void assertNotNull(Object object) 檢查對象不為空 |
5 | void assertNull(Object object) 檢查對象為空 |
6 | void assertSame(boolean condition) assertSame() 方法檢查兩個相關對象是否指向同一個對象 |
7 | void assertNotSame(boolean condition) assertNotSame() 方法檢查兩個相關對象是否不指向同一個對象 |
8 | void assertArrayEquals(expectedArray, resultArray) assertArrayEquals() 方法檢查兩個數(shù)組是否相等 |
下面我們在例子中試驗一下上面提到的各種方法。創(chuàng)建一個文件名為 TestAssertions.java 的類
import org.junit.Test;
import static org.junit.Assert.*;
public class TestAssertions {
@Test
public void testAssertions() {
//test data
String str1 = new String ("abc");
String str2 = new String ("abc");
String str3 = null;
String str4 = "abc";
String str5 = "abc";
int val1 = 5;
int val2 = 6;
String[] expectedArray = {"one", "two", "three"};
String[] resultArray = {"one", "two", "three"};
//Check that two objects are equal
assertEquals(str1, str2);
//Check that a condition is true
assertTrue (val1 < val2);
//Check that a condition is false
assertFalse(val1 > val2);
//Check that an object isn't null
assertNotNull(str1);
//Check that an object is null
assertNull(str3);
//Check if two object references point to the same object
assertSame(str4,str5);
//Check if two object references not point to the same object
assertNotSame(str1,str3);
//Check whether two arrays are equal to each other.
assertArrayEquals(expectedArray, resultArray);
}
}
接下來,創(chuàng)建一個文件名為 TestRunner.java 的類來執(zhí)行測試用例:
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner2 {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestAssertions.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
注解Annotation
注解就好像你可以在你的代碼中添加并且在方法或者類中應用的元標簽。JUnit 中的這些注釋為我們提供了測試
方法的相關信息,哪些方法將會在測試方法前后應用,哪些方法將會在所有方法前后應用,哪些方法將會在執(zhí)行
中被忽略。
JUnit 中的注解的列表以及他們的含義:
序號 | 注釋和描述 |
---|---|
1 | @Test 這個注釋說明依附在 JUnit 的 public void 方法可以作為一個測試案例。 |
2 | @Before 有些測試在運行前需要創(chuàng)造幾個相似的對象。在 public void 方法加該注釋是因為該方法需要在 test 方法前運行。 |
3 | @After 如果你將外部資源在 Before 方法中分配,那么你需要在測試運行后釋放他們。在 public void 方法加該注釋是因為該方法需要在 test 方法后運行。 |
4 | @BeforeClass 在 public void 方法加該注釋是因為該方法需要在類中所有方法前運行。 |
5 | @AfterClass它將會使方法在所有測試結束后執(zhí)行。這個可以用來進行清理活動。 |
6 | @Ignore這個注釋是用來忽略有關不需要執(zhí)行的測試的。 |
下創(chuàng)建一個文件名為 JunitAnnotation.java 的類來測試注釋
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class JunitAnnotation {
//execute before class
@BeforeClass
public static void beforeClass() {
System.out.println("in before class");
}
//execute after class
@AfterClass
public static void afterClass() {
System.out.println("in after class");
}
//execute before test
@Before
public void before() {
System.out.println("in before");
}
//execute after test
@After
public void after() {
System.out.println("in after");
}
//test case
@Test
public void test() {
System.out.println("in test");
}
//test case ignore and will not execute
@Ignore
public void ignoreTest() {
System.out.println("in ignore test");
}
}
創(chuàng)建一個文件名為 TestRunner.java 的類來執(zhí)行注解
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(JunitAnnotation.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
運行結果
in before class
in before
in test
in after
in after class
true
觀察以上的輸出,這是 JUnite 執(zhí)行過程:
- beforeClass() 方法首先執(zhí)行,并且僅執(zhí)行一次。
- afterClass() 方法最后執(zhí)行,并且僅執(zhí)行一次。
- before() 方法在每個測試用例執(zhí)行之前執(zhí)行。
- after() 方法在每個測試用例執(zhí)行之后執(zhí)行。
- 在 before() 方法和 after() 方法之間,執(zhí)行每個測試用例。
JUnitCore 執(zhí)行測試
下面是 org.junit.runner.JUnitCore 類的聲明:
public class JUnitCore extends java.lang.Object
測試用例是使用 JUnitCore 類來執(zhí)行的。JUnitCore 是運行測試的外觀類。它支持運行 JUnit 4 測試。 要從命令行運行測試,可以運行 java org.junit.runner.JUnitCore 。對于只有一次的測試運行,可以使用靜態(tài)方法 runClasses(Class[])。文章來源:http://www.zghlxwxcb.cn/news/detail-769333.html
下節(jié)介紹
【JUnit技術專題】「入門到精通系列」手把手+零基礎帶你玩轉單元測試,讓你的代碼更加“強壯”(場景化測試篇)文章來源地址http://www.zghlxwxcb.cn/news/detail-769333.html
到了這里,關于【JUnit技術專題】「入門到精通系列」手把手+零基礎帶你玩轉單元測試,讓你的代碼更加“強壯”(實戰(zhàn)開發(fā)篇)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!