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!"); }));
}