2017-04-07 172 views
0

如何使用espresso編寫以下代碼的測試用例。我點擊一個圖標時會執行以下代碼。 我知道,我可以檢查的推出意圖的使用目的(toPackage(....並可能嘲笑的意圖,如果它是通過startActivityForResult推出,但如何處理這種情況下推出的結果。使用Espresso進行測試

try { 
intent = new Intent(Intent.ACTION_DIAL); 
intent.setData(Uri.parse("tel:" +"xxxxxx"); // 12 digit mobile no 
    if (intent.resolveActivity(context.getPackageManager()) != null) { 
         startActivity(intent) 
     } 
    } 
catch (Exception e) { 
    Toast.makeText(getActivity(), "No phone number available", Toast.LENGTH_SHORT).show(); 
       } 

回答

2

的答案是使用「預期」的方法測試代碼後,驗證活動的結果符合您的要求,看起來像這樣:

@Test 
public void typeNumber_ValidInput_InitiatesCall() { 
    // Types a phone number into the dialer edit text field and presses the call button. 
    onView(withId(R.id.edit_text_caller_number)) 
      .perform(typeText(VALID_PHONE_NUMBER), closeSoftKeyboard()); 
    onView(withId(R.id.button_call_number)).perform(click()); 

    // Verify that an intent to the dialer was sent with the correct action, phone 
    // number and package. Think of Intents intended API as the equivalent to Mockito's verify. 
    intended(allOf(
      hasAction(Intent.ACTION_CALL), 
      hasData(INTENT_DATA_PHONE_NUMBER), 
      toPackage(PACKAGE_ANDROID_DIALER))); 
} 

但是,作爲一個完全自動化測試的一部分,你需要將活動的響應也刪除,以便它可以在沒有實際阻止用戶輸入的情況下運行。您需要設置inten運行測試上前t存根:

@Before 
    public void stubAllExternalIntents() { 
     // By default Espresso Intents does not stub any Intents. Stubbing needs to be setup before 
     // every test run. In this case all external Intents will be blocked. 
     intending(not(isInternal())).respondWith(new ActivityResult(Activity.RESULT_OK, null)); 
    } 

然後,你可以這樣寫測試的相應部分:

@Test 
    public void pickContactButton_click_SelectsPhoneNumber() { 
     // Stub all Intents to ContactsActivity to return VALID_PHONE_NUMBER. Note that the Activity 
     // is never launched and result is stubbed. 
     intending(hasComponent(hasShortClassName(".ContactsActivity"))) 
       .respondWith(new ActivityResult(Activity.RESULT_OK, 
         ContactsActivity.createResultData(VALID_PHONE_NUMBER))); 

     // Click the pick contact button. 
     onView(withId(R.id.button_pick_contact)).perform(click()); 

     // Check that the number is displayed in the UI. 
     onView(withId(R.id.edit_text_caller_number)) 
       .check(matches(withText(VALID_PHONE_NUMBER))); 
    } 

如果需要從其他應用程序(如電話撥號與實際用戶輸入驗證),這超出了Espresso的範圍。由於我目前與一家幫助處理這類案件的供應商合作,我不願意提供名稱和工具,但很多人確實需要編寫模擬真實端到端體驗的測試。

邁克埃文斯有一個很好的關於測試意圖here的文章,並且總是有android文檔here

+0

我真的很感激你的答案,但我正在尋找解決問題的方法,我們使用startActivity而不是startActivityForResult啓動撥號器活動。我曾經使用過類似的策略來嘲笑Camera Intent – cammando