zoukankan      html  css  js  c++  java
  • Writing Your First Test

    Let's say you have an activity layout that represents a welcome screen:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <Button
            android:id="@+id/login"
            android:text="Login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    
    </LinearLayout>
    

    We want to write a test that asserts that when a user clicks on a button, the app launches the LoginActivity.

    //我们想要测试的是当用户点击了button,应用是否启动了LoginActivity

    public class WelcomeActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.welcome_activity);
    
            final View button = findViewById(R.id.login);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(WelcomeActivity.this, LoginActivity.class));
                }
            });
        }
    }
    

    In order to test this, we can check that when a user clicks on the "Login" button, we start the correct intent. Because Robolectric is a unit testing framework, the LoginActivity will not actually be started, but we can check that the WelcomeActivity fired the correct intent:

    //为了测试这一点,我能够检查当用户点击了button时我们开启了正确的intent,因为robolectric是单元测试框架,LoginActivity并没有真的被启动,但是我们能够检查WelcomeActivity是否开启了正确的intent

    @RunWith(RobolectricTestRunner.class)
    public class WelcomeActivityTest {
    
        @Test
        public void clickingLogin_shouldStartLoginActivity() {
            WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class);
            activity.findViewById(R.id.login).performClick();
    
            Intent expectedIntent = new Intent(activity, LoginActivity.class);
            assertThat(shadowOf(activity).getNextStartedActivity()).isEqualTo(expectedIntent);
        }
    }
    ----------- Do not start just casually, and do not end just casually. -----------
  • 相关阅读:
    Linux官方源、镜像源汇总
    python3 pip报错 TypeError: 'module' object is not callable
    2019-11-27:kali 2019-4中文乱码解决方法
    2019-11-26:密码学基础知识,csrf防御
    2019-11-25:信息收集,笔记
    2019-11-24:postgresql数据库安装,最后报错failed to load SQLModule 问题的解决方案
    2019-11-22:xss绕过笔记
    2019-11-20:xss学习笔记
    2019-11-19:无返回的盲型xxe,使用带外读取数据
    2019-11-19:xxe漏洞利用,笔记
  • 原文地址:https://www.cnblogs.com/yexiant/p/5691939.html
Copyright © 2011-2022 走看看