1. Never use Selenium FIT mode
Selenium分為兩種運(yùn)行模式,Driven Mode(現(xiàn)在叫Selenium Remote Control)和FIT Mode(現(xiàn)在叫Selenium Core)。
	FIT Mode顧名思義,是類似FIT Testing Framework那種使用方式,主要用于QA等非技術(shù)人員編寫Web應(yīng)用的功能測(cè)試。FIT Mode的Selenium測(cè)試使用HTML來(lái)組織測(cè)試用例。例如我要測(cè)試一個(gè)web應(yīng)用的登陸功能。我可能寫出這樣的HTML 表格。
	 1 < table >
	 2 < tr >
	 3   < td > open </ td >
	 4          < td > http://localhost:8080/login </ td >
	 5          < td ></ td >
	 6 </ tr >
	 7 < tr >
	 8   < td > type </ td >
	 9          < td > id=username </ td >
	10          < td > someuser </ td >
	11 </ tr >
	12 < tr >
	13   < td > type </ td >
	14          < td > id=password </ td >
	15          < td > password </ td >
	16 </ tr >
	17 < tr >
	18   < td > click </ td >
	19          < td > id=login_button </ td >
	20          < td ></ td >
	21 </ tr >
	22 < tr >
	23   < td > assertTextPresent </ td >
	24          < td > Welcome to xxxx </ td >
	25          < td ></ td >
	26 </ tr >
	27 </ table >
不同于FIT,Selenium內(nèi)置了一系列的命令,如上例中的open, type, click以及assertTextPresent,因此QA可以完全拋開DEV獨(dú)立地編寫測(cè)試(FIT需要DEV提供Behavior Fixture)。因此FIT Mode是相當(dāng)容易使用的,哪怕不會(huì)使用HTML的QA,也可以使用FrontPage畫出三列表格,依次填入數(shù)據(jù)。
	然而對(duì)于大多數(shù)team而言——尤其是敏捷team,F(xiàn)IT Mode平易的外表下是令人恐懼的泥沼。大多數(shù)團(tuán)隊(duì)往往選擇使用Selenium作為功能測(cè)試和集成測(cè)試工具而不僅僅是QA測(cè)試工具,在不同的迭代間遇到功能流程或UI變化時(shí),必須要重構(gòu)Selenium測(cè)試,或者說,F(xiàn)unctional Test Migration。令人遺憾的是,HTML based的Selenium FIT Testing的重構(gòu)竟然令人難以置信的困難。我們可以使用include等Selenium FIT擴(kuò)展,使得它可以重用詳細(xì)的功能(Log in, Log out諸如此類)。即便如此,在一個(gè)真實(shí)的項(xiàng)目中,Selenium Test的數(shù)量往往在200-500之間(我目前所處的項(xiàng)目在改用Driven Mode前已達(dá)350+),對(duì)于這么大基數(shù)的Selenium測(cè)試,手工重構(gòu)幾乎是不可想象的,而目前尚沒有HTML代碼重構(gòu)工具。即便存在泛泛意義上的HTML重構(gòu)工具,對(duì)于Selenium測(cè)試重構(gòu)的有效性尚待商榷。而使用Driven Mode上述代碼可以寫為:
	1 public   void  testShouldShowAWeclomeMessageAfterUserLoggedIn()  {
	2     selenium.open( " http://localhost:8080/login " );
	3     selenium.type( " id=username " , " someuser " );
	4     selenium.type( " id=password " ,  " password " );
	5     selenium.click( " id=login_button " );
	6     assertTrue(selenium.isTextPresent( " Welcome to xxxx " ));
	7 }
	
	很自然,一個(gè)訓(xùn)練有素的程序員會(huì)重構(gòu)出如下代碼:
	 1 public   void  login(String username, String password)  {
	 2     selenium.open( " http://localhost:8080/login " );
	 3     selenium.type( " id=username " ,username);
	 4     selenium.type( " id=password " , password);
	 5     selenium.click( " id=login_button " );
	 6 }
	 7
	 8 public   void  testShouldShowAWeclomeMessageAfterUserLoggedIn()  {
	 9     login( " someuser " ,  " password " );
	10     assertTrue(selenium.isTextPresent( " Welcome to xxxx " ));
	11 }
之后無(wú)論是pull up到公共基類還是extact到Utils class都是很容易的事情。由于Java在代碼重構(gòu)上便利,Java Selenium Remote Control成為使用Selenium的佳方式。在這一點(diǎn)上,縱使Ruby語(yǔ)法上比Java簡(jiǎn)單靈活得多,它仍不是編寫Selenium測(cè)試的佳載體(當(dāng)然一個(gè)經(jīng)過精心設(shè)計(jì)的ruby selenium dsl wrapper還是具有非凡的價(jià)值的,這個(gè)我們后面會(huì)涉及到)。