→前置作業:安裝STS&可建立Gradle Project←
(STS&Gradle Project非絕對必要,在此僅以此建立範例)
一、專案建立
(1) File > New > Project
(2) Gradle > Gradle Project
(3) 輸入Project name(自取),Sample project選Java Quickstart
二、設定JUnit
(1) 專案按右鍵 > Build Path > Configure Build Path
(2) Libraries > Add Library
(3) 選到JUnit > Next
(4) 選擇JUnit 4 > Finish
(5) 新增好JUnit 4
三、建立測試檔案
(1) src/main/java/按右鍵 > New > Package
(2) src/main/java/按右鍵 > New > Package
前述建立的package按右鍵 > New > Class
四、 編寫測試程式
(1) 建立一個method
package com.tsots.junit;
public class JunitTest {
public class TestNum{
public boolean isBigger(int num) {
System.out.println("傳入"+num);
int origin = 555;
if(num > origin){
return true;
//return "Yes";
}else{
return false;
}
}
}
}
(2) 加上@Test表示這是一個測項,記得
import org.junit.Assert;
import org.junit.Test;
@Test
public void test1(){
TestNum testNum = new TestNum();
Assert.assertEquals(true, testNum.isBigger(567));
}
@Test
public void test2(){
TestNum testNum = new TestNum();
Assert.assertEquals(true, testNum.isBigger(123));
}
(3) 欲測試的.java上按滑鼠右鍵 > Run As > JUnit Test
(4) 看結果
這裡告訴你第28行呼叫的method回傳了false,所以在此JUnit Test呈現fail
五、更多應用
@Before :表示會在每一個@test前先執行一次
@After :表示會在每一個@test後再執行一次
@BeforeClass :表示會在執行class前會先執行一次
@AfterClass :表示執行完class後會執行一次
(1) 加上@BeforeClass、@Before、@AfterClass、@After,記得
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
@BeforeClass
public static void beforeClass(){
System.out.println("beforeClass");
}
@Before
public void before(){
System.out.println("before");
}
@AfterClass
public static void afterClass(){
System.out.println("afterClass");
}
@After
public void after(){
System.out.println("after");
}
(2) 欲測試的.java上按滑鼠右鍵 > Run As > JUnit Test
(3) 看結果
通常會在
1. @Before
setUp()←初始化物件
2. @Test
測試方法
3. tesrDown()←釋放測試下物件
總網頁瀏覽量
基礎Note
☪About Me
(1)
免費軟體
(2)
教學
(4)
教學文件
(42)
會計軟體
(1)
電腦系統
(1)
Adapter
(8)
Adobe Premiere
(1)
AlertDialog
(7)
Android App 介紹
(1)
Animation
(1)
API
(2)
APP範例
(1)
Array
(1)
AsyncTask
(1)
Auto Test Case
(32)
AutoCompleteTextView
(1)
Bitmap Drawable
(3)
BroadcastReceiver
(4)
Button
(1)
Codility
(2)
Contact
(4)
DB
(1)
Dialog
(2)
Documents
(1)
Eclipse
(3)
Ellipsize
(1)
File
(4)
Focus
(2)
Fragment
(4)
Gallery
(2)
GIT
(4)
GitHub
(1)
GridView
(8)
HashMap
(1)
HorizontalScrollView
(6)
IIS
(1)
Intent
(3)
IntentService
(1)
Internet
(2)
KeyEvent
(1)
Layout
(1)
ListView
(11)
Log
(1)
Mac / iOS
(11)
Manifest
(1)
Marquee
(2)
Math
(1)
MediaPlayer
(5)
MediaRecorder
(5)
MSMQ
(1)
onClick
(1)
PackageManager
(6)
PHP
(1)
PIS
(3)
PowerManager
(1)
Progress
(2)
SCREEN
(1)
Search
(6)
Service
(1)
SharedPreferences
(3)
SimpleDateFormat
(1)
SonarQube
(1)
Sound Recorder
(1)
Spinner
(2)
SQL server Management
(16)
SQLite
(13)
String
(1)
STS
(5)
SVN
(1)
Thread
(1)
Toast
(3)
Typeface
(1)
Uri
(2)
VB.NET
(17)
VMware
(1)
沒有留言:
張貼留言