1. 程式人生 > >用JUnit4進行單元測試程式碼編寫

用JUnit4進行單元測試程式碼編寫

JUnit4簡介

Junit是一個可編寫重複測試的簡單框架,是基於Xunit架構的單元測試框架的例項。JUnit4是JUnit框架有史以來的最大改進,其主要目標便是利用JDK 5的Annotation特性簡化測試用例的編寫。JDK 5裡可以靜態匯入,例如import static org.junit.Assert.*;。Annotation又稱註解(或元資料),其實就是@Before、@After、@BeforeClass、@AfterClass、@Test等等。

@Before @BeforeClass @After @AfterClass的區別

簡單來說,@[email protected]

會在每一個被@Test註解的方法前、後分別執行,比如有5個被@Test註解的方法,那麼@[email protected]會被執行5次。被@[email protected]註解的方法一般起到初始化和釋放的作用。這麼做就保證了每一次@Test執行,他們都是相互獨立,互不干擾的。
而@[email protected]從頭至尾僅會執行一次。對於那些較耗資源的,建議採用這種方法。
當然二者還有很多其他區別,詳見部落格:
http://blog.163.com/[email protected]/blog/static/9606199220129682521489/

@Test執行順序

一般來說,被@Test註解的方法是隨機順序執行的,因為單元測試,本身它們就應該是互不干擾可以獨立執行的。
但是某些特殊情況下,想讓它按照一定順序執行的話,可以使用@FixMethodOrder(MethodSorters.NAME_ASCENDING),放在JUnit測試類定義的外面,這樣一來就會按照方法名稱的升序來執行。此時命好方法的名字,就可以輕鬆實現既定順序執行。

更多關於JUnit4

JUnit4程式碼塊

將JUnit4測試類放在被測類的同一package下,讓它們處於同一層級,這樣就不用import被測類了。

package pkg_Selector;
import
org.junit.*; import org.junit.runners.MethodSorters; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import static org.junit.Assert.*; /** * Created by Sophie on 15/7/6. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SelectorTest { private static Selector s; private static WebDriver afterLogin; private static WebDriver afterSwitch; private static WebDriver aftermouseMove; private static WebDriver afterSearch; private static WebDriver afterSelect; @BeforeClass public static void setUp() throws Exception { s = new Selector(); } @AfterClass public static void tearDown() throws Exception { s.tearDown(); } @Test public void test1_login() throws Exception { afterLogin = s.login(); assertEquals("挖財社群,國內最大的理財社群", afterLogin.getTitle()); } @Test public void test2_switchWindow() throws Exception { afterSwitch = s.switchWindow(); assertEquals("理財規劃_理財學院_挖財社群,國內最大的理財社群,愛理財的人都在這裡",afterSwitch.getTitle()); } @Test public void test3_mouseMove() throws Exception { aftermouseMove = s.mouseMove(); assertEquals("使用者",aftermouseMove.findElement(By.cssSelector("a.showmenu.xg1")).getText()); } @Test public void test4_search() throws Exception { afterSearch = s.search(); assertEquals("查詢好友 - 挖財社群",afterSearch.getTitle()); } @Test public void test5_select() throws InterruptedException { afterSelect = s.select(); assertEquals(true,afterSelect.getPageSource().contains("以下是查詢到的使用者列表(最多顯示 100 個)")); } }

JUnit4執行結果截圖

5個test都是通過的:
這裡寫圖片描述

被測程式碼塊

package pkg_Selector;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;

import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by Sophie on 15/7/6.
 */
public class Selector {
    private WebDriver dr;
    private String url;
    private String account;
    private String pwd;

    public Selector() {
        this.url = "https://www.wacai.com/user/user.action?url=http%3A%2F%2Fbbs.wacai.com%2Fportal.php";
        //Scanner input = new Scanner(System.in);
        //System.out.println("Please input the account");
        this.account = "******";//input.next();
        //System.out.println("Please input the password");
        this.pwd = "******";//input.next();
        this.dr = new FirefoxDriver();
        this.dr.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    }


    public WebDriver login( ) throws Exception {
        //登入
        dr.get(url);
        dr.findElement(By.id("account")).clear();
        dr.findElement(By.id("account")).sendKeys(account);
        dr.findElement(By.id("pwd")).clear();
        dr.findElement(By.id("pwd")).sendKeys(pwd);
        dr.findElement(By.id("login-btn")).click();
        return dr;
    }

    public WebDriver switchWindow() throws Exception {
        //開啟理財規劃子版塊
        String a = dr.findElement(By.linkText("理財規劃")).getAttribute("href");
        //直接用WebDriver.get()方式開啟頁面,瀏覽器不會新開頁面,省得切換視窗
        dr.get(a);
        dr.manage().window().maximize();
        //然後關閉左側導航欄
        dr.findElement(By.cssSelector("a.comiis_left_closes")).click();
        return dr;
    }

    public WebDriver mouseMove() throws Exception {

        //點開搜尋型別下拉框,將滑鼠移動到使用者上並選擇
        Actions act = new Actions(dr);
        WebElement dropDown = dr.findElement(By.cssSelector("a.showmenu.xg1"));
        WebElement user = dr.findElement(By.cssSelector("ul#comiis_twtsc_type_menu>li>a[rel='user']"));
        act.click(dropDown).perform();
        act.moveToElement(user).click().perform();
        act.moveByOffset(20, 30).click().perform();
        return dr;
    }

    public WebDriver search() throws Exception {
        //找到搜尋輸入框,並輸入關鍵字,然後點選搜尋按鈕
        WebElement input = dr.findElement(By.id("comiis_twtsc_txt"));
        input.clear();
        input.sendKeys("周杰倫");
        dr.findElement(By.id("comiis_twtsc_btn")).click();//Click之後FireFox新開了一個頁面

        //用WindowHandle+頁面title來切換dr至我們想要的視窗
        String currentWindow = dr.getWindowHandle();
        Set<String> handles = dr.getWindowHandles();
        //System.out.println(handles.size());
        Iterator h = handles.iterator();
        while (h.hasNext()) {
            dr = dr.switchTo().window((String) h.next());
            //System.out.println(dr.getTitle());
            if (dr.getTitle().equals("查詢好友 - 挖財社群"))
                break;
        }
        return dr;
    }

    public WebDriver select() throws InterruptedException {
        dr.findElement(By.cssSelector("html>body#nv_home.pg_spacecp.sour>div#wp.wp.cl>div#ct.ct2_a.wp.cl>div.mn>div.bm.bw0>ul.tb.cl>li:nth-child(2)>a")).click();
        /*用普通定位+click方式處理下拉框
        dr.findElement(By.xpath("//select[@id='resideprovince']/option[@value='浙江省']")).click();
        Thread.sleep(2000);
        dr.findElement(By.xpath("//select[@id='residecity']/option[@value='杭州市']")).click();
        */
        //用Select方式
        Select sProvince = new Select(dr.findElement(By.xpath("//select[@id='resideprovince']")));
        sProvince.selectByValue("浙江省");
        Thread.sleep(2000);
        Select sCity = new Select(dr.findElement(By.xpath("//select[@id='residecity']")));
        sCity.selectByValue("杭州市");
        dr.findElement(By.cssSelector("button.pn")).click();
        return dr;
    }

    public void tearDown() throws Exception {
        dr.quit();
    }
    public static void main(String[] args) throws Exception {
        Selector s = new Selector();
        s.login();
        s.switchWindow();
        s.mouseMove();
        s.search();
        WebDriver selectPage = s.select();
        //xpath模糊查詢
        List<WebElement> searchResult = selectPage.findElements(By.cssSelector("li.bbda.cl"));
        System.out.println("搜尋到" + searchResult.size() + "個同城使用者,他們是:");
        System.out.printf("%-20s %-20s %-20s\n", "使用者名稱", "使用者等級", "使用者積分");
        String userName;
        String userLevel;
        String userMark = "";
        String[] sArray;
        for (int i = 0; i < searchResult.size(); i++) {
            sArray = searchResult.get(i).findElement(By.cssSelector("li>p")).getText().split(" ");
            if (sArray.length < 2)
                userMark = "0";
            else
                userMark = sArray[3];
            userLevel = sArray[0];
            userName = searchResult.get(i).findElement(By.cssSelector("h4>a")).getText();
            System.out.printf("%-20s %-20s %-20s\n",userName,userLevel,userMark);

            s.tearDown();
        }
    }
}