2016-08-24 116 views
2

假設我讓一個抽象BaseActivityToolbar,像這樣:如何使用Espresso測試抽象類?

/** 
* A base activity that handles common functionality in the app. 
* This includes the Toolbar 
*/ 
public abstract class BaseActivity extends AppCompatActivity { 
    // Primary toolbar 
    private Toolbar mToolbar; 

    @Override 
    public void setContentView(int layoutResId) { 
     super.setContentView(layoutResId); 
     setToolbar(); 
    } 

    private void setToolbar() { 
     if (mToolbar == null) { 
      mToolbar = (Toolbar) findViewById(R.id.toolbar); 
      if (mToolbar != null) {    
       mToolbar.setNavigationContentDescription(getResources().getString(
        R.string.navigation_drawer_description_ally)); 
      setSupportActionBar(mToolbar); 
      } 
     } 
    } 
} 

和延伸這個BaseActivity一個MainActivity,像這樣:

public class MainActivity extends BaseActivity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 
} 

的佈局是:

toolbar.xml

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v7.widget.Toolbar 
xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/toolbar" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="?attr/colorPrimary" 
    android:elevation="@dimen/spacing_tiny" 
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" 
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light" 
    android:fitsSystemWindows="true" 
    android:minHeight="?attr/actionBarSize" 
    > 

</android.support.v7.widget.Toolbar> 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context=".MainActivity" 
    > 

    <include 
     layout="@layout/toolbar" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     /> 

</LinearLayout> 

我的問題是:如何測試BaseActivity使用espresso?例如,要檢查Toolbar是否存在?

回答

2

您應該創建TestActivity以測試您的抽象BaseActivity類。但請記住,該類只應覆蓋必要的方法和代碼,以避免對BaseActivity類產生任何影響。

public class TestActivity extends BaseActivity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 
} 

然後你就可以用你的咖啡要

@RunWith(AndroidJUnit4.class) 
@SmallTest 
public class BaseActivityTest { 
    @Rule 
    public ActivityTestRule<TestActivity> mTestActivityActivityTestRule = new ActivityTestRule<TestActivity>(TestActivity.class, true, false); 
    @Before 
    public void set() { 
     //setup your things 
    } 
    @Test 
    public void testRequest1() { 
     mTestActivityActivityTestRule.launchActivity(new Intent()); 
    } 
}