How do I test abstract classes with Espresso?… here is a solution to the problem.
How do I test abstract classes with Espresso?
Suppose I created an abstract with Toolbar
BaseActivity
, like this:
/**
* 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);
}
}
}
}
There is also a MainActivity
that extends this BaseActivity
as follows:
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The layout is:
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>
My question is: how to test BaseActivity with espresso
? For example, check if the toolbar
exists?
Solution
You should create a TestActivity to test your abstract BaseActivity class. Keep in mind, however, that this class should only cover the necessary methods and code to avoid any impact on the BaseActivity class.
public class TestActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Then you can use Espresso
@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());
}
}