久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

Android測試基礎(chǔ)整理篇

 tracyf 2015-11-24

Android test framework


轉(zhuǎn)載請注明來自:http://blog.csdn.net/liaoqianchuan00/article/details/23032357


1.  基本


1.  常用Assertions


l   assertEquals


l   assertFalse?


l   assertNotNull


l   assertNotSame


l   assertNull


l   assertSame


l   assertTrue


l   fail


 


2.  自定義輸出語句









public void testMax() {


final int a = 1;


final int b = 2;


final int expected = b;


final int actual = Math.max(a, b);


assertEquals("Expection " + expected + " but was " + actual, expected,   actual);


}



3.   控件Assertions


l   assertBaselineAligned: Asserts that two views arealigned on their baseline, that is their baselines are on the same y location.


l   assertBottomAligned: Asserts that two views arebottom aligned, that is their bottom edges are on the same y location.


l   assertGroupContains: Asserts that the specifiedgroup contains a specific child once and only once.


l   assertGroupIntegrity: Asserts the specified group'sintegrity. The children count should be >= 0 and each child should benon-null.


l   assertGroupNotContains: Asserts that the specifiedgroup does not contain a specific child.


l   assertHasScreenCoordinates: Asserts that a view hasa particular x and y position on the visible screen.


l   assertHorizontalCenterAligned: Asserts that the testview is horizontally center aligned with respect to the reference view.


l   assertLeftAligned: Asserts that two views are leftaligned, that is their left edges are on the same x location. An optionalmargin can also be provided.


l   assertOffScreenAbove: Asserts that the specifiedview is above the visible screen.


l   assertOffScreenBelow: Asserts that the specifiedview is below the visible screen.


l   assertOnScreen: Asserts that a view is on thescreen.


l   assertRightAligned: Asserts that two views areright-aligned, that is their right edges are on the same x location. Anoptional margin can also be specified.


l   assertTopAligned: Asserts that two views aretop-aligned, that is their top edges are on the same y location. An optionalmargin can also be specified.


l   assertVerticalCenterAligned: Asserts that the testview is vertically center aligned with respect to the reference view.


 


4.  TouchUtils


l   Clicking on a View and releasing it


l   Tapping on a View, that is touching it and quicklyreleasing


l   Long clicking on a View


l   Dragging the screen


 


 


 









public void testListScrolling() {


       mListView.scrollTo(0, 0);


       TouchUtils.dragQuarterScreenUp(this, mActivity);


       TouchUtils.dragQuarterScreenUp(this, mActivity);


       TouchUtils.dragQuarterScreenUp(this, mActivity);


       TouchUtils.dragQuarterScreenUp(this, mActivity);


       TouchUtils.tapView(this, mListView);


       final int expectedItemPosition = 6;


       final int actualItemPosition =


         mListView.getFirstVisiblePosition();


       assertEquals("Wrong position",


         expectedItemPosition, actualItemPosition);


       final String expected = "Anguilla";


       final String actual = mListView.getAdapter().


         getItem(expectedItemPosition).toString();


       assertEquals("Wrong content", actual, expected);


}



 


5.  Mock對象


l   MockApplication: A mock implementation of the Application class. All methods arenon-functional and throw UnsupportedOperationException.


l   MockContentProvider: A mock implementation of ContentProvider. All methods arenon-functional and throw UnsupportedOperationException.


l   MockContentResolver: A mock implementation of the ContentResolver class that isolatesthe test code from the real content system. All methods are non-functional andthrow UnsupportedOperationException.


l   MockContext: A mock Context class. This can be used to inject otherdependencies. All methods are non-functional and throwUnsupportedOperationException.


l   MockCursor: A mock Cursor class that isolates the test code from real Cursorimplementation. All methods are non-functional and throwUnsupportedOperationException.


l   MockDialogInterface: A mock implementation of DialogInterface class. All methods arenon-functional and throw UnsupportedOperationException.


l   MockPackageManager: A mock implementation of PackageManager class. All methods arenon-functional and throw UnsupportedOperationException.


l   MockResources: A mock Resources class. All methods are non-functional and throw UnsupportedOperationException.


2.  框架結(jié)構(gòu)


1     AndroidTestCase



 


當你需要用到Activity Context的時候就使用這個類,,比如Resources,database,,file system,,你可以是用mContext來是用context。你可以用ontext.startActivity()來啟動多個Activity,。


有很多個testcase繼承自這個類:


l   ApplicationTestCase<T extends Application>


l   ProviderTestCase2<T extends ContentProvider>


l  ServiceTestCase<T extends Service>


 


2     Instrumentation


這個是用來監(jiān)視Activity和Application的,,你可以用它來控制Activity的生命周期和用戶交互事件。


 


l   我們可以是用Instrumentation.ActivityMonitor來監(jiān)測一個Activity,。例如:









public void testFollowLink() {


final Instrumentation inst = getInstrumentation();


IntentFilter intentFilter = new IntentFilter(Intent.ACTION_VIEW);


intentFilter.addDataScheme("http");


intentFilter.addCategory(Intent.CATEGORY_BROWSABLE);


ActivityMonitor monitor = inst.addMonitor(


IntentFilter, null, false);


assertEquals(0, monitor.getHits());


TouchUtils.clickView(this, mLink);              monitor.waitForActivityWithTimeout(5000);


assertEquals(1, monitor.getHits()); inst.removeMonitor(monitor);


}



 


l   使用Instrumentation來測試activities,,它的生命周期的函數(shù)不會自動調(diào)用,只有onCreate方法會自動調(diào)用,,你可以調(diào)用其他的生命周期通過getInstrumentation().callActivityOnXXX,。


3     InstrumentationTestCase






它的子類:


l   ActivityTestCase


l   ProviderTestCase2<T extends ContentProvider>


l   SingleLaunchActivityTestCase<T extends Activity>


l   SyncBaseInstrumentation


l   ActivityInstrumentationTestCase2<T extends Activity>


l   ActivityUnitTestCase<T extends Activity>


 



注意:android.test.ActivityInstrumentationTestCase從Android1.5開始已經(jīng)不建議使用了,,可以是用android.test.ActivityInstrumentationTestCase2替代。



 


3.  例子程序


1.  被測試程序









package com.vogella.android.test.simpleactivity;


 


import android.app.Activity;


import android.content.Intent;


import android.os.Bundle;


import android.view.View;


 


public class MainActivity extends Activity {


 


  @Override


  protected void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);


    setContentView(R.layout.activity_main);


  }


 


  public void onClick(View view) {


    Intent intent = new Intent(this, SecondActivity.class);


    intent.putExtra("URL", "http://www.");


    startActivity(intent);


  }


}



 


 


2.  單元測試









package com.vogella.android.test.simpleactivity.test;


 


import android.content.Intent;


import android.test.TouchUtils;


import android.test.suitebuilder.annotation.SmallTest;


import android.widget.Button;


 


import com.vogella.android.test.simpleactivity.MainActivity;


 


public class MainActivityUnitTest extends


    android.test.ActivityUnitTestCase<MainActivity> {


 


  private int buttonId;


  private MainActivity activity;


 


  public MainActivityUnitTest() {


    super(MainActivity.class);


  }


  @Override


  protected void setUp() throws Exception {


    super.setUp();


    Intent intent = new Intent(getInstrumentation().getTargetContext(),


        MainActivity.class);


    startActivity(intent, null, null);


    activity = getActivity();


  }


 


  public void testLayout() {


    buttonId = com.vogella.android.test.simpleactivity.R.id.button1;


    assertNotNull(activity.findViewById(buttonId));


    Button view = (Button) activity.findViewById(buttonId);


    assertEquals("Incorrect label of the button", "Start", view.getText());


  }


 


  public void testIntentTriggerViaOnClick() {


    buttonId = com.vogella.android.test.simpleactivity.R.id.button1;


    Button view = (Button) activity.findViewById(buttonId);


    assertNotNull("Button not allowed to be null", view);


 


    view.performClick();


   


    // TouchUtils cannot be used, only allowed in


    // InstrumentationTestCase or ActivityInstrumentationTestCase2


 


    // Check the intent which was started


    Intent triggeredIntent = getStartedActivityIntent();


    assertNotNull("Intent was null", triggeredIntent);


    String data = triggeredIntent.getExtras().getString("URL");


 


    assertEquals("Incorrect data passed via the intent",


        "http://www.", data);


  }


 


}



 


3.  功能測試









package com.vogella.android.test.simpleactivity.test;


 


import android.app.Activity;


import android.app.Instrumentation;


import android.app.Instrumentation.ActivityMonitor;


import android.test.ActivityInstrumentationTestCase2;


import android.test.TouchUtils;


import android.test.ViewAsserts;


import android.view.KeyEvent;


import android.view.View;


import android.widget.Button;


import android.widget.TextView;


 


import com.vogella.android.test.simpleactivity.R;


 


import com.vogella.android.test.simpleactivity.MainActivity;


import com.vogella.android.test.simpleactivity.SecondActivity;


 


public class MainActivityFunctionalTest extends


    ActivityInstrumentationTestCase2<MainActivity> {


 


  private MainActivity activity;


 


  public MainActivityFunctionalTest() {


    super(MainActivity.class);


  }


  @Override


  protected void setUp() throws Exception {


    super.setUp();


    setActivityInitialTouchMode(false);


    activity = getActivity();


  }


 


  public void testStartSecondActivity() throws Exception {


   


   


   


    // add monitor to check for the second activity


    ActivityMonitor monitor =


        getInstrumentation().


          addMonitor(SecondActivity.class.getName(), null, false);


 


    // find button and click it


    Button view = (Button) activity.findViewById(R.id.button1);


   


    // TouchUtils handles the sync with the main thread internally


    TouchUtils.clickView(this, view);


 


    // to click on a click, e.g., in a listview


    // listView.getChildAt(0);


 


    // wait 2 seconds for the start of the activity


    SecondActivity startedActivity = (SecondActivity) monitor


        .waitForActivityWithTimeout(2000);


    assertNotNull(startedActivity);


 


    // search for the textView


    TextView textView = (TextView) startedActivity.findViewById(R.id.resultText);


   


    // check that the TextView is on the screen


    ViewAsserts.assertOnScreen(startedActivity.getWindow().getDecorView(),


        textView);


    // validate the text on the TextView


    assertEquals("Text incorrect", "Started", textView.getText().toString());


   


    // press back and click again


    this.sendKeys(KeyEvent.KEYCODE_BACK);


   


    TouchUtils.clickView(this, view);


  }


}



 


 


Robotium


https://code.google.com/p/robotium/wiki/RobotiumTutorials下載例子程序


 









public void testDisplayWhiteBox() {


 


              //Defining our own values to multiply


              float vFirstNumber = 10;


              float vSecondNumber = 20;


              float vResutl = vFirstNumber * vSecondNumber ;


             


              //Access First value (edit-filed) and putting firstNumber value in it


              EditText vFirstEditText = (EditText) solo.getView(R.id.EditText01);


              solo.clearEditText(vFirstEditText);


              solo.enterText(vFirstEditText, String.valueOf(vFirstNumber));


             


              //Access Second value (edit-filed) and putting SecondNumber value in it


              EditText vSecondEditText = (EditText) solo.getView(R.id.EditText02);


              solo.clearEditText(vSecondEditText);


              solo.enterText(vSecondEditText, String.valueOf(vSecondNumber));


             


              //Click on Multiply button


              solo.clickOnButton("Multiply");


             


              assertTrue(solo.searchText(String.valueOf(vResutl)));                         


              TextView outputField = (TextView) solo.getView(R.id.TextView01);          


              //Assert to verify result with visible value


              assertEquals(String.valueOf(vResutl), outputField.getText().toString());


       }



 


參考地址:


https://code.google.com/p/robotium/


 


https://code.google.com/p/robotium/wiki/RobotiumTutorials


 


1     簡介


Robotium是一款國外的Android自動化測試框架,,主要針對Android平臺的應(yīng)用進行黑盒自動化測試,,它提供了模擬各種手勢操作(點擊、長按,、滑動等),、查找和斷言機制的API,能夠?qū)Ω鞣N控件進行操作,。Robotium結(jié)合Android官方提供的測試框架達到對應(yīng)用程序進行自動化的測試,。另外,,Robotium 4.0版本已經(jīng)支持對WebView的操作,。Robotium 對Activity,Dialog,,Toast,,Menu 都是支持的。


 


類似于selenium,。


 


2     API


Solo類中提供了自動點擊,、取得、拖拽,、搜索等各種方法,。 聲明Solo類型的成員變量privateSolo solo;  


 


Activity&Fragment


assertCurrentActivity(text,Activity.class)- Ensure that the current activity equals the second parameter.


getCurrentActivity() .getFragmentManager().findFragmentById()-S earches for a fragment.


waitForActivity(SecondActivity.class,2000)- Waits for the specified activity for 2 seconds


點擊 


clickOnButton(int)—Clickson a Button with a given index.


clickOnButton(String)—Clickson a Button with a given text. clickOnCheckBox(int)—Clicks on a CheckBox with agiven index.  clickOnView(View)—Clicks ona given View.  


clickOnText(String)—Clickson a View displaying a given text. clickLongOnText(String)—Long clicks on agiven View. clickOnRadioButton(int)—Clicks on a RadioButton with a given index.clickOnScreen(float, float)—Clicks on a given coordinate on the
screen.


clickInList(x);-Click on item number x in a ListView


clickOnSearch-Allows to click on part of the screen.


pressSpinnerItem(0,2);-Presses an item in a Spinner


sendKey(Solo.MENU);-Sends the menu key event.


goBack()-Pressthe back button


取得 


getCurrentActivity()—Returnsthe current Activity.  


GetText(String)—Returnsa TextView which shows a given text. 


getView(int)—Returnsa View with a given id.  


getEditText(String)—Returnsan EditText which shows a given text.  getImage(int)—Returns an ImageView with a given index. 


 


拖拽


drag(float,float, float, float, int)—Simulate touching a given location and dragging it toa new location.


 


搜索


searchText(String)—Searchesfor a text string and returns true if at least one item is found with theexpected text.


searchEditText(String)—Searchesfor a text string in the EditText objects located in the current Activity.   S


earchButton(String,boolean)—Searches for a Button with the given text string and returns true ifat least one Button is found.


waitForText(text)


輸入


enterText()-Entersa text.


 


界面判斷


isCheckBoxChecked()-Checksif the checkbox is checked.


 


截屏


takeScreenshot()-Savesa screenshot on the device inthe /sdcard/Robotium-Screenshots/ folder. Requiresthe android.permission.WRITE_EXTERNAL_STORAGE permission in theAndroidManifest.xml ofthe application under test.


 


 


 


4.  QA


1.    在不知道ID的情況下怎么獲取特定的view?


答:例如,,ArrayList<TextView> aa = solo.getCurrentViews(TextView.class),, 然后斷點調(diào)試查看是哪個view,TextViewtextview = aa.get(5);


 


2.    如何滾動和拖動,?


答:solo.scrollXXX();solo.drag(初始X坐標,目標X坐標,Y,toY,步數(shù)); X,,Y坐標可以通過HierarchyViewer工具獲得,也可以通過Year.getLocationOnScreen(zuobiao),。


 


3.    Robotium和robolectric區(qū)別,?


答:Robotium是通過ui線程進行測試,一般用于對應(yīng)傳統(tǒng)的集成或系統(tǒng)測試,;


Robolectric 是單元測試框架,,好處是第一運行在JVM上,速度,、性能高,;


解決了Android自身因為環(huán)境問題的缺點以及減少了許多用Mock的地方。


 


4. 如何識別webview對象,?


答:可以根據(jù)XPATH來進行點擊和輸入


solo.clickOnWebElement(By.xpath(text));


solo.enterTextInWebElement(By.xpath(text),s);


或者根據(jù)ID來獲取


solo.clickOnWebElement(By.id(text));


solo.enterTextInWebElement(By.id(text), s);


 


 


Mockito


1.  簡介


流行的mock框架


 


# jMock


http:///


# EasyMock


http:///


# Mockito


http://code.google.com/p/mockito/


 


使用Mockito不能用在下面的情況:


final classes


anonymous classes


primitive types


 


2.  使用方法


when(....).thenReturn(....)


或者


doReturn(object).when(kdskfsk).methodCall


 


 


使用verify來保證方法被調(diào)用到了


 


例如:


 









@Test


public void test1()  {


  MyClass test = Mockito.mock(MyClass.class);


  // define return value for method getUniqueId()


  test.when(test.getUniqueId()).thenReturn(43);


 


  // TODO use mock in test....


 


  // now check if method testing was called with the parameter 12


  Mockito.verify(test).testing(Matchers.eq(12));


 


  // was the method called twice?


  Mockito.verify(test, Mockito.times(2));


 


 


}



 


3.  Mock和Spy的區(qū)別


如果你mock了一個類,,那么這個類的所有的函數(shù)都被Mockito改寫了(如果是沒有返回值的函數(shù),,則什么都不作,如果是有返回值,,會返回默認值,,比如布爾型的話返回false,List的話會返回一個空的列表,,int的話會返回0等等),,如果你Spy了一個類,那么所有的函數(shù)都沒有被改變,,除了那些被你打過樁的函數(shù),。看例子:


 









public class TestServiceImpl 



    public int getOrderCounts() 


    { 


        return 10; 


    } 



@Test 


    public void MockVsSpy() 


    { 


        TestServiceImpl service = mock(TestServiceImpl.class); 


        //輸出0,,因為該函數(shù)被Mockito改寫了 


        System.out.println("Order counts of mock object" + service.getOrderCounts()); 


        when(service.getOrderCounts()).thenReturn(2); 


        //輸出2,, 因為我們給這個函數(shù)打了樁 


        System.out.println("Order counts of mock object AFTER stubs " + service.getOrderCounts()); 


         


        service = new TestServiceImpl(); 


        service = spy(service); 


        //輸出10, 因為Mockito spy 不會改寫已有的函數(shù) 


        System.out.println("Order counts of spy object" + service.getOrderCounts()); 


        when(service.getOrderCounts()).thenReturn(2); 


        //輸出2,, 因為我們給這個函數(shù)打了樁 


        System.out.println("Order counts of spy object AFTER stubs " + service.getOrderCounts()); 


    } 



 


4.    如何寫自定義的參數(shù)匹配器


看例子









public class Account 



    private String    name; 


    private String    adddress; 


 


    public Account(String name, String address) 


    { 


        this.name = name; 


        this.adddress = address; 


    } 


    ...get/set 函數(shù) 



public interface AccountDao 



    public void addAccount(Account a); 



 


public class AccountServiceImpl 



    AccountDao dao; 


     


    public AccountServiceImpl(AccountDao dao) 


    { 


        this.dao = dao; 


    } 


     


    public void addAccount(String name, String address) 


    { 


        dao.addAccount(new Account(name, address)); 


    } 



 


 


public class AccountServiceImplTest 



    @Test 


    public void addAccount() 


    { 


        AccountDao dao = mock(AccountDao.class); 


        AccountServiceImpl service = new AccountServiceImpl(dao); 


         


        service.addAccount("obama", "white house"); 


         


        verify(dao).addAccount(new Account("obama", "white house")); 


    } 




上面的例子會失敗,,因為Mockito在做參數(shù)匹配時是根據(jù)equals函數(shù)的結(jié)果來判斷兩個參數(shù)是不是一樣的。而我們的Account類并沒有對equals作特殊的實現(xiàn),,所以會失敗,。修正的方法有三個,一個是改寫Account類的equals函數(shù),。一個是用Mockito的反射相等匹配,,就是把最后一句改成。


 









verify(dao).addAccount(refEq(new Account("obama", "white house")));


 



 


最后一種方法是寫一個自定義的參數(shù)匹配器,,如果Account的代碼不是你控制的,,那么你就只能選這種方法了。這時候最后一句要改成這樣:









verify(dao).addAccount(argThat(new ArgumentMatcher<Account>() 


        { 


            @Override 


            public boolean matches(Object argument) 


            { 


                Account person = (Account)argument; 


                return person.getName().equals("obama") && person.getAddress().equals("white house") ? true : false; 


            } 


        })); 



 


在Android中使用Mockito:


需要下載下面3個庫文件,。


http://dexmaker./files/dexmaker-1.0.jar


http://dexmaker./files/dexmaker-mockito-1.0.jar


https://code.google.com/p/mockito/


 



 


  

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點,。請注意甄別內(nèi)容中的聯(lián)系方式,、誘導(dǎo)購買等信息,謹防詐騙,。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多