如何在 Android Studio 中创建测试? [英] How can I create tests in Android Studio?

查看:69
本文介绍了如何在 Android Studio 中创建测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚下载了基于 Intellij Idea 的 Android Studio.

如何创建测试?

我注意到有一个用于创建测试模块的选项,但这似乎没有任何作用,只能使用 src 创建一个新项目

我还尝试按下热键 CTRL+AlT+T,它允许在现有类上创建单元测试,但它似乎想将它放在当前项目中.当然这对 TDD 没有帮助

有人在这方面有经验吗?

解决方案

这个答案适用于刚开始使用 Android 测试的人.我将提供两个简单的示例来帮助您了解测试的工作原理.如果您按照接下来的 10 分钟进行操作,您就可以开始将测试添加到您自己的应用程序中了.我想你会惊讶它是多么容易.我当然是.

Android 测试简介

您将进行两种不同类型的测试.

  • 本地单元测试.这些在 JVM(Java 虚拟机)上本地运行.由于它们是本地的,因此速度很快.您可以使用它们来测试只需要 Java 而不是 Android API 的代码部分.(有时你可以制作一个虚假的 API 对象来在本地测试更多的东西.这称为

    一切都已经存在,等着你来创建你的测试.一切都已经安排好了!

    如何创建本地单元测试

    打开上图中显示的 ExampleUnitTest 文件.它应该看起来像这样:

    公共类 ExampleUnitTest {@测试public void additional_isCorrect() 抛出异常 {assertEquals(4, 2 + 2);}}

    按绿色双箭头运行所有测试或按绿色单箭头仅运行一个.(在这种情况下,只有一个测试,所以他们都做同样的事情.)

    它应该通过(只要在阅读此答案时 2 + 2 仍然是 4 ).恭喜,您刚刚进行了第一次测试!

    进行自己的测试

    让我们编写自己的测试.首先将此类添加到您的主应用程序项目中,以便我们进行测试:

    public class MyClass {公共 int add(int a, int b) {返回 a + b;}}

    现在将测试类中的 addition_isCorrect() 方法更改为如下代码(或者只是添加另一个具有不同名称的方法):

    公共类 ExampleUnitTest {@测试public void additional_isCorrect() 抛出异常 {MyClass myClass = new MyClass();int 结果 = myClass.add(2, 2);int 预期 = 4;assertEquals(预期,结果);}}

    再次运行它,您应该会看到它通过.恭喜,您刚刚创建了自己的第一个测试!(好吧,我想从技术上讲它是我的,但是,嘿,足够接近了.我的就是你的.)

    如何创建仪器化测试

    打开 ExampleInstrumentedTest 文件.它应该看起来像这样:

    @RunWith(AndroidJUnit4.class)公共类 ExampleInstrumentedTest {@测试public void useAppContext() 抛出异常 {//被测应用的上下文.上下文 appContext = InstrumentationRegistry.getTargetContext();assertEquals("com.example.myapp", appContext.getPackageName());}}

    再次按下其中一个绿色按钮.

    只要您连接了真实设备或设置了模拟器,它就应该已启动并运行您的应用程序.恭喜,您刚刚运行了第一个仪器测试!

    进行自己的测试

    检测测试使用

    启动后,单击模拟器中的按钮,然后在记录"对话框中选择确定"完成.它应该自动生成以下测试代码.

    @LargeTest@RunWith(AndroidJUnit4.class)公共类 MainActivityTest {@规则公共 ActivityTestRulemActivityTestRule = new ActivityTestRule<>(MainActivity.class);@测试公共无效 mainActivityTest() {ViewInteraction appCompatButton = onView(allOf(withId(R.id.myButton), withText(点击我"), isDisplayed()));appCompatButton.perform(click());}}

    太好了!您刚刚创建了第一个插桩测试!那太容易了.您可能应该添加一个断言以使其成为真正的测试,但这对记录器也很容易做到.观看此视频以深入了解.

    进一步研究

    我会先观看视频,然后通读文档.这一切都非常有帮助.最后一个链接指向一系列文章,这些文章涵盖了在选择测试内容时需要考虑的一些重要事项.

    Just downloaded Android Studio which is based off of the Intellij Idea.

    How would one create tests?

    I notice there is a option for create a Test Module but this doesn't seem to do anything, only create a new project with src

    I also tried pressing the hot key CTRL+AlT+T which allows to create unit tests on an existing class but it seems to want to place it in the current project. Of course this doesn't help with TDD

    Does anyone have any experience here ?

    解决方案

    This answer is for people who are just getting started with Android testing. I will provide two simple examples to help you see how testing works. If you follow along for the next 10 minutes, you will be all set up to start adding your tests to your own app. I think you'll be surprised how easy it is. I certainly was.

    Intro to Android Testing

    There are two different types of tests that you will do.

    • Local unit tests. These are run locally on the JVM (Java Virtual Machine). Since they are local, they are fast. You can use them to test the parts of your code that just need Java and not the Android APIs. (Sometimes you can make a fake API object to test more things locally. This is called a mocking. A mock Context is an example.)
    • Instrumented tests. These tests are run on a real device or in the emulator. That makes them slower than the local tests. However, they are more flexible because you have the full Android API available to you.

    Create a new project and you will see the following default folders.

    Everything is already there and waiting for you to create your tests. It's all set up already!

    How to create local unit tests

    Open the ExampleUnitTest file shown in the image above. it should look something like this:

    public class ExampleUnitTest {
        @Test
        public void addition_isCorrect() throws Exception {
            assertEquals(4, 2 + 2);
        }
    }
    

    Press the double green arrow to run all the tests or the single green arrow to run only one. (In this case there is only one test so they both do the same thing.)

    It should pass (as long as 2 + 2 is still 4 when you are reading this answer). Congratulations, you just ran your first test!

    Making your own test

    Let's write our own test. First add this class to your main app project so that we have something to test:

    public class MyClass {
        public int add(int a, int b) {
            return a + b;
        }
    }
    

    Now change the addition_isCorrect() method in the test class to be like the following code (or just add another method with a different name):

    public class ExampleUnitTest {
        @Test
        public void addition_isCorrect() throws Exception {
            MyClass myClass = new MyClass();
            int result = myClass.add(2, 2);
            int expected = 4;
            assertEquals(expected, result);
        }
    }
    

    Run it again and you should see it pass. Congratulations, you just created your own first test! (Well, I guess technically it was mine, but, hey, close enough. What's mine is yours.)

    How to create instrumented tests

    Open the ExampleInstrumentedTest file. it should look something like this:

    @RunWith(AndroidJUnit4.class)
    public class ExampleInstrumentedTest {
        @Test
        public void useAppContext() throws Exception {
            // Context of the app under test.
            Context appContext = InstrumentationRegistry.getTargetContext();
    
            assertEquals("com.example.myapp", appContext.getPackageName());
        }
    }
    

    Press one of those green buttons again.

    As long as you have a real device connected or the emulator set up, it should have started it up and run your app. Congratulations, you just ran your first instrumented test!

    Making your own test

    The instrumented tests use Espresso to run the tests. It is kind of like your own little robot user that you can have test your app. You can tell it to do something like pressing a button or reading the properties of a TextView.

    You can write the instructions for how to do the test by hand, but since we are just starting out, let's use the auto-record function. It's super simple.

    First add a button to your UI so that we have something to work with. I did this:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
        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"
        tools:context="com.example.myapp.MainActivity">
    
        <Button
            android:id="@+id/myButton"
            android:text="Click me"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    
    </android.support.constraint.ConstraintLayout> 
    

    Then press Run > Record Espresso Test in the menu.

    After it starts, click the button in the emulator and then to finish choose OK on the Record dialog. It should auto generate the following test code.

    @LargeTest
    @RunWith(AndroidJUnit4.class)
    public class MainActivityTest {
    
        @Rule
        public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
    
        @Test
        public void mainActivityTest() {
            ViewInteraction appCompatButton = onView(
                    allOf(withId(R.id.myButton), withText("Click me"), isDisplayed()));
            appCompatButton.perform(click());
        }
    }
    

    Great! You just created you first instrumented test! That was super easy. You should probably add an assertion to make it a real test, but that that is pretty easy to do with the recorder, too. Watch this video to go a little deeper.

    Further Study

    I'd watch the videos first and then read through the documentation. It is all pretty helpful. The last link is to a series of articles that cover some important things to think about when choosing what to test.

    这篇关于如何在 Android Studio 中创建测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆