2016-12-07 40 views
0

我使用JUnit轉輪的Cucumber。我使用Appium進行App UI測試,但這對於這個問題應該沒有關係。相關部分是我想跨iOS和Android重用功能和步驟定義,並且將Selenium驅動程序實例從JUnit傳遞到步驟,因爲我只想啓動一次測試服務器。從JUnit Runner傳遞上下文到黃瓜步驟

我有這樣的事情:

login.feature

Feature: Login 
@android_phone @ios_phone 
Scenario: Successful login 
    Given ... 

CucumberIOSTest.java

@RunWith(Cucumber.class) 
@CucumberOptions(
     glue = {"classpath:my.stepdefinitions"}, 
     tags = {"@ios_phone,@ios_tablet"} 
) 
public class CucumberIOSTest { 

    private static WebDriver driver; 

    @BeforeClass 
    public static void setUp() throws Exception { 
     // setup code that starts up the ios simulator via appium 
     driver = DriverFactory.createIOSDriver(); 
    } 

    @AfterClass 
    public static void tearDown() { 
     // shutdown ios simulator 
    } 

} 

而且幾乎相同的Android CucumberAndroidTest.java

@RunWith(Cucumber.class) 
@CucumberOptions(
     glue = {"classpath:my.stepdefinitions"}, 
     tags = {"@android_phone,@android_tablet"} 
) 
public class CucumberAndroidTest { 

    private static WebDriver driver; 

    @BeforeClass 
    public static void setUp() throws Exception { 
     // setup code that starts up the android simulator via appium 
     driver = DriverFactory.createAndroidDriver(); 
    } 

    @AfterClass 
    public static void tearDown() { 
     // shutdown android simulator 
    } 

} 

步驟位於GenericSteps.java(現在只有一個文件):

public class GenericSteps { 
    public GenericSteps(WebDriver driver) { 
     this.driver = driver; 
    } 

    @Given("^...$") 
    public void ...() throws Throwable { 
     ... 
    } 
} 

我怎樣才能在driverCucumberIOSTest/CucumberAndroidTest的步驟構造通?

問題是隻有CucumberIOSTest/CucumberAndroidTest實例知道我是否想測試iOS或Android標記。 GenericSteps不知道這一點。另外,我只想分別在每個平臺上爲所有測試啓動一次模擬器。

我試過DI,但是我沒有找到方法來通過我在JUnit Runner中創建的WebDriver實例。有任何想法嗎?

回答

1

我認爲最簡單的解決方案是使用Singleton設計模式。 DriverFactory必須始終返回相同的WebDriver實例。所以在你的DriverFactory裏添加'靜態WebDriver實例'和getWebDriver()方法。

public final class DriverFactory { 
    private static WebDriver instance = null; 

    public static synchronized WebDriver getWebDriver() { 
     if (instance == null) {throw RuntimeException("create WebDriver first")}; 
     return instance; 
    } 
    public static synchronized WebDriver createAndroidDriver() { 
     if (instance == null) { 
     // setup code that starts up the android simulator via appium 
     instance = yourWebDriver 
     } 
     return instance; 
    } 
    ... 
}  

現在您GenericSteps CAL是這樣的:

public class GenericSteps { 
    public GenericSteps() { 
     this.driver = DriverFactory.getWebDriver(); 
    } 

    @Given("^...$") 
    public void ...() throws Throwable { 
     ... 
    } 
} 
+0

嗯,實際工作,謝謝!我只需要重置'@ AfterClass'中的WebDriver實例,所以當我第一次運行iOS測試,然後運行Android測試時,它就能正常工作。 – fabb