2017-02-06 82 views
0

我有一些測試需要從終端運行,但是我需要能夠選擇指向我的API調用而不是實況的URL。有沒有辦法在終端上做到這一點?動態更改網址Android Studio

目前我在我的Constants.java文件中有一個字符串,我指向不同的字符串,但我需要從終端顯然執行它!所以我的字符串是private static String BASE_URL = "http://www.website.com/"這是我想在終端中改變的字符串。

我寫了以下內容,但似乎沒有要求我輸入任何內容。

@Before 
    public void setURLForAPICalls() { 
     Scanner url_input = new Scanner(System.in); 
     System.out.print("Enter the server you wish to test against: "); 
     Constants.BASE_URL = url_input.next(); 
} 

即使很@Before測試方法或一些設置它的情況?我一直在試圖弄清楚這幾天,並開始認爲這是不可能做...

在此先感謝!

+0

什麼意思由_apparently_做?如果您發佈代碼以便我們可以看到發生了什麼,這將會很有幫助。 – px06

+0

您可以將參數傳遞給主方法並由其解析。相關問題在這裏:http://stackoverflow.com/questions/890966/what-is-string-args-parameter-in-main-method-java –

+0

@ px06由顯然,我做aha。我沒有代碼張貼因爲我不知道該怎麼做! – BilalMH

回答

1

從你的問題你已經指出,在Constants.java你有下面的語句:

private static String BASE_URL = "http://www.website.com/"; 

當你考,你試圖改變這種BASE_URL,你不能這樣做。它不僅是一個private成員或Constants,但它也是一個final成員,這意味着它的價值不能改變。

你可以做的是創建實例化Constants當你的應用程序運行,你可以指定它是一個TESTRELEASE版本。

像下面這樣可能就足夠了:

public enum RUN_TYPE { 
    TEST, 
    RELEASE; 
} 

您可以通過修改Constants類是類似以下內容:

public class Constants { 

    private static final instance = new Constants(); 

    private RUN_TYPE type; 

    private String BASE_URL; 

    // More urls here 

    private Constants(){ 

    } 

    public void setRunType(RUN_TYPE type){ 
     this.type = type; 
     if(type == RUN_TYPE.RELEASE){ 
      BASE_URL = "http://release.api/endpoints"; 
     } else if(type == RUN_TYPE.TEST){ 
      BASE_URL = "http://test.api/endpoints"; 
     } 
    } 

    public String getBaseUrl(){ 
     return BASE_URL; 
    } 

    public static Constants getInstance(){ 
     return instance; 
    } 

    // More getters here 

} 

這是一個單例類將包含所需的值如您所述。

在釋放模式中,你可以撥打:

Constants.getInstance().setRunType(RUN_TYPE.RELEASE); 

雖然測試你可以這樣做:

@RunWith(AndroidJUnit4.class) 
public class TestSomething { 


    @BeforeClass 
    public static void runOnce(){ 
     Constants.getInstance().setRunType(RUN_TYPE.TEST); 
    } 

    @Test 
    public void testOne(){ 
     // tests 
    } 
} 
0

同時通過CLI執行測試,您可以傳遞參數。

例如,如果你想在執行測試通過URL,你可以這樣做:

am instrument -w -r -e URL "http://www.google.com" -e debug false -e class com.example.android.TestClassName com.example.android.test/android.support.test.runner.AndroidJUnitRunner 

爲了獲取在測試中相同的值,你可以使用:

InstrumentationRegistry.getArguments().getString("URL") 

欲瞭解更多信息,你可以看到這裏-eTest from the Command Line