Open Browser trên java 8

Nơi các bạn có thể tìm thấy mọi thông tin cần thiết về Selenium testing tool
Forum rules
Nơi trao đổi, chia sẻ thông tin liên quan đến testing tool Selenium.
Nên search trước khi post bài.
Post Reply
cuhavp
Jr. Tester
Posts: 61
Joined: Mon 21 Jan, 2013 3:52 pm
Contact:

Open Browser trên java 8

Post by cuhavp »

Một trong nhưng hàm mình hay gọi là common function hay selenium owner method là hàm openBrowser.
Thường thì các dự án làm selenium hiện nay đều hỗ trợ cross browser tức là trang web có thể chạy được trên nhiều trình duyệt khác nhau.
Để viết một hàm với mục đích trên thì giải pháp mà nhiều bạn nghĩ tới đầu tiên là sử dụng hàm switch/case hoặc hàm if/else để có thể cover được nhiều trường hợp.

Java 8 là một trong nhứng version mà có nhiều cải tiến nhât của java để có thể cạnh tranh cũng như kế thừa lại một số feature mà các ngôn ngữ lâp trình khác như C# hoặc python.
Ở bài này mình giới thiệu một các để tối ưu hoá đươc hàm này dựa trên nền của java8 và thư viện javaslang.

Code: Select all

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import static javaslang.API.*;
import static javaslang.Predicates.*;
....
public static WebDriver openBrowser() {
		return Match(System.getProperty("browser")).of(
				Case(anyOf(isNull(), String::isEmpty), () -> { throw new IllegalStateException("'browser' property is missing!"); }),
				Case(CHROME::equalsIgnoreCase, () -> new ChromeDriver()),
				Case(FIREFOX::equalsIgnoreCase, () -> new FirefoxDriver()),
				Case($(), browser -> { throw new IllegalArgumentException(browser + " browser is not supported!"); }));
	}



cuhavp
Jr. Tester
Posts: 61
Joined: Mon 21 Jan, 2013 3:52 pm
Contact:

Re: Open Browser trên java 8

Post by cuhavp »

Code: Select all

public static WebDriver openBrowserUsingSwitch() {
    final String browser = System.getProperty("browse");
    if (browser == null || browser.isEmpty()) {
      throw new IllegalStateException("'browser' property is missing!");
    }
    switch (browser) {
      case CHROME:
        return new ChromeDriver();
      case FIREFOX:
        return new FirefoxDriver();
      default:
        throw new IllegalArgumentException(browser + " browser is not support");
    }
  }

  public static WebDriver openBrowser() {
    return Match(
            System.getProperty("browser")).of(
            Case(CHROME::equalsIgnoreCase, () -> new ChromeDriver()),
            Case(FIREFOX::equalsIgnoreCase, () -> new FirefoxDriver()),
            Case(IE::equalsIgnoreCase, () -> new InternetExplorerDriver()),
            Case(SAFARI::equalsIgnoreCase, () -> new SafariDriver()),
            Case(EDGE::equalsIgnoreCase, () -> new EdgeDriver()),
            Case($(), browser -> {throw new IllegalArgumentException(browser + " browser is not supported!");})
    );
  }



Post Reply

Return to “Selenium”