[Selenium] 於 Eclipse 建立 test case

之前的示範中已經嘗試了如何自動化進行測試. 現在開始撰寫Test case, 以將需要測試的進行自動化. 而在Eclipse 進行的話, 則需要安裝TestNG 套件.於Eclipse安裝TestNG

  1. 加入TestNG repository.
    於Eclipse 中, 選取 Help > Install New Software > Add, 並輸入以下內容後按OK

    Name TestNG
    Location http://beust.com/eclipse/

  2. 安裝TestNG 套件.
    於Work with 選取新加的Repository 後, 選取TestNG 再按 Finish.
  3. 建立Test case.
    建立一個新class, 命名為SampleTest, 並輸入以下代碼.

    import static org.testng.Assert.assertTrue;
    
    import java.util.concurrent.TimeUnit;
    
    import org.openqa.selenium.By;
    import org.openqa.selenium.Keys;
    import org.openqa.selenium.WebDriver;
    import org.testng.annotations.AfterMethod;
    import org.testng.annotations.BeforeMethod;
    import org.testng.annotations.Test;
    
    public class SampleTest  {
    	private static final String TEST_URL="http://www.google.com";
    	
    	private WebDriver _driver;
    		
    	@BeforeMethod
    	public void beforeMethod() {
    		_driver=WebDriverBuilder.BuildChromeDriver();
    		_driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    	}
    	
    	@AfterMethod
    	public void afterMethod() {
    		_driver.close();
    	}
    	
    	@Test
    	public void searchInGoogle() {
    		_driver.get(TEST_URL);
    		_driver.findElement(By.id("lst-ib")).sendKeys("Apple");
    		_driver.findElement(By.name("btnK")).sendKeys(Keys.RETURN);
    		
    		assertTrue(_driver.getPageSource().indexOf("IPhone") >0);
    	}
    }
  4. 進行測試.
    於Test case 中右鍵, 選取Run As… > TestNG Test, 執行若見到以下結果, 代表測試成功.
About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.