使用浓缩咖啡测试启动活动意图

时间:2018-01-22 12:53:34

标签: android android-espresso android-testing

我想进行简单的UI测试,按下按钮并启动活动。

我试过基于this documentation.(android开发者)

SplashActivity代码:

public class SplashActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    findViewById(R.id.launch_register_activity_btn).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(SplashActivity.this, RegisterActivity.class);
            startActivity(intent);
        }
    });
}
}

测试代码:

@RunWith(AndroidJUnit4.class)
public class SimpleIntentTest {

@Rule
public IntentsTestRule<SplashActivity> intentsRule = new IntentsTestRule<>(SplashActivity.class);

@Test
public void newActivityLaunchingTest() {


    onView(withId(R.id.launch_register_activity_btn)).perform(click());

    Log.i("register-package_name", RegisterActivity.class.getPackage().toString());
    Log.i("register-class_name", RegisterActivity.class.getName());
    Log.i("register-short_name", RegisterActivity.class.getSimpleName());


    intended(allOf(
            hasComponent(hasShortClassName(".RegisterActivity")),
            toPackage("re.example.common")
    ));


}
}

logcat的:

01-22 13:37:51.615: I/register-package_name(25292): package re.example.common, Unknown, version 0.0
01-22 13:37:51.615: I/register-class_name(25292): re.example.common.RegisterActivity
01-22 13:37:51.615: I/register-short_name(25292): RegisterActivity

包结构:

enter image description here

测试输出:

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: Wanted to match 1 intents. Actually matched 0 intents.

IntentMatcher: (has component: has component with: class name: an instance of java.lang.String package name: an instance of java.lang.String short class name: is ".RegisterActivity" and resolvesTo: re.example.common)

Matched intents:[]

无论我如何尝试,测试都不会验证我是否已启动RegisterActivity 。测试失败。

据我所知,我确实喜欢上面链接中的浓缩咖啡测试示例。

我做错了什么?

我也尝试过:

1。删除。 (点)来自“.RegisterActivity”

intended(allOf(
            hasComponent(hasShortClassName("RegisterActivity")),
            toPackage("re.example.common")
    ));

2。删除。 (点)来自“.RegisterActivity” toPackage(“re.example.common”)

intended(allOf(
            hasComponent(hasShortClassName("RegisterActivity"))
    ));

我的RegisterActivity的包名是“re.example.common.RegisterActivity”名称为“RegisterActivity”。不是吗?

为什么测试失败?

这里发生了什么,我误解或误解了什么?

提前致谢。

1 个答案:

答案 0 :(得分:1)

应用程序ID (应用程序包名称为)是: re.example.common.RegisterActivity(来源gradle)

活动的全名是:hasShortClassName

这样,.common.RegisterActivity意味着.RegisterActivity短名称而非RegisterActivity也不是{{1}}

咩。