gpt4 book ai didi

java - 如何使用 Espresso 测试抽象类?

转载 作者:太空宇宙 更新时间:2023-11-03 13:47:50 25 4
gpt4 key购买 nike

假设我用 Toolbar 创建了一个抽象的 BaseActivity ,像这样:

/**
* 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);
}
}
}
}

还有一个扩展此 BaseActivityMainActivity,如下所示:

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>

我的问题是:如何使用 espresso 测试 BaseActivity ?例如,检查 Toolbar 是否存在?

最佳答案

您应该创建一个 TestActivity 来测试您的抽象 BaseActivity 类。但请记住,此类应仅覆盖必要的方法和代码,以避免对 BaseActivity 类产生任何影响。

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

然后您可以使用 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());
}
}

关于java - 如何使用 Espresso 测试抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39113061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com