java 如何在 Android Studio 1.1 中运行简单的 JUnit4 测试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28843304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:16:01  来源:igfitidea点击:

How to run a simple JUnit4 test in Android Studio 1.1?

javaandroidunit-testingjunitandroid-studio

提问by EGHDK

I have an Android project that shows "Hello World". It was created from the "Blank Activity" template from Android Studio.

我有一个显示“Hello World”的 Android 项目。它是从 Android Studio 的“Blank Activity”模板创建的。

I then add/create a new java class in my application package (the same package that has my activity). I call it Shape and add a simple constructor

然后我在我的应用程序包(与我的活动相同的包)中添加/创建一个新的 java 类。我称之为 Shape 并添加一个简单的构造函数

public class Shape {
    public Shape(int i){
        if (i==0){
            throw new IllegalArgumentException("Cant have 0");
        }
    }
}

Great. Now I have a class that isn't touching Android at all, and I want to unit test it. What should I do next?

伟大的。现在我有一个根本不涉及 Android 的类,我想对其进行单元测试。我接下来该怎么做?

This is where my question stops. Below I'll go through what I tried.

这是我的问题停止的地方。下面我将通过我的尝试。

Please note that I really have never tested before in Android or Java. Excuse me for "rookie" mistakes.

请注意,我之前确实从未在 Android 或 Java 中进行过测试。请原谅我的“菜鸟”错误。

  1. While in the Shape.java I go to "Navigate" > "Test"
  2. Hit enter to select "Create new Test"
  3. Get this popup, and select JUNIT4.
  1. 在 Shape.java 中,我转到“导航”>“测试”
  2. 按回车键选择“创建新测试”
  3. 获取此弹出窗口,然后选择 JUNIT4。

enter image description here

在此处输入图片说明

  1. I then hit the fix button to fix the library not being found
  2. I get this popup
  1. 然后我点击修复按钮来修复未找到的库
  2. 我得到这个弹出窗口

enter image description here

在此处输入图片说明

  1. I'm not really sure what to select, so I select the default/highlighted.
  2. I write my test

    package com.eghdk.getjunit4towork;
    
    import org.junit.Test;
    
    import static org.junit.Assert.*;
    
    public class ShapeTest {
        @Test(expected = IllegalArgumentException.class)
        public void testShapeWithInvalidArg() {
            new Shape(0);
        }
    }
    
  3. At this point, I'm not really sure how to run my tests, but try to do this: enter image description here

  4. I get these errors when running

    Error:(3, 17) Gradle: error: package org.junit does not exist
    Error:(5, 24) Gradle: error: package org.junit does not exist
    Error:(8, 6) Gradle: error: cannot find symbol class Test

  1. 我不确定要选择什么,所以我选择了默认/突出显示。
  2. 我写我的测试

    package com.eghdk.getjunit4towork;
    
    import org.junit.Test;
    
    import static org.junit.Assert.*;
    
    public class ShapeTest {
        @Test(expected = IllegalArgumentException.class)
        public void testShapeWithInvalidArg() {
            new Shape(0);
        }
    }
    
  3. 在这一点上,我不太确定如何运行我的测试,但尝试这样做: 在此处输入图片说明

  4. 运行时出现这些错误

    错误:(3, 17) Gradle: 错误: 包org.junit 不存在
    错误:(5, 24) Gradle: 错误: 包org.junit 不存在
    错误:(8, 6) Gradle: 错误: 找不到符号课堂测试

回答by nhaarman

Since Android Studio 1.1, there is (experimental) unit test support. A couple of quotes from that page:

从 Android Studio 1.1 开始,有(实验性)单元测试支持。来自该页面的几句话:

You will have to specify your testing dependencies in the build.gradle file of your android module. For example:

dependencies {
  testCompile 'junit:junit:4.12'
  testCompile "org.mockito:mockito-core:1.9.5"
}

To use unit testing support in AS, you have to do the following steps:

  1. Update build.gradle to use the android gradle plugin version 1.1.0-rc1 or later (either manually in build.gradle file or in the UI in File > Project Structure)

  2. Add necessary testing dependencies to app/build.gradle (see above).

  3. Enable the unit testing feature in Settings > Gradle > Experimental.

  4. Sync your project.

  5. Open the "Build variants" tool window (on the left) and change the test artifact to "Unit tests".

  6. Create a directory for your testing source code, i.e. src/test/java. You can do this from the command line or using the Project view in the Project tool window. The new directory should be highlighted in green at this point. Note: names of the test source directories are determined by the gradle plugin based on a convention.

  7. Create your test. You can do this by opening a class, right-clicking its name and selecting "Go to > Test". Add some test cases.
  8. Right click your new test class or method and select "Run ...".
  9. (Optional) You can decrease the compilation time by using Gradle directly. To do this, go to the Run menu and select "Edit configurations". There, find the default JUnit template, remove the "Make" before-launch step and add a "Gradle aware make" step instead (leave the task name empty).

您必须在 android 模块的 build.gradle 文件中指定测试依赖项。例如:

dependencies {
  testCompile 'junit:junit:4.12'
  testCompile "org.mockito:mockito-core:1.9.5"
}

要在 AS 中使用单元测试支持,您必须执行以下步骤:

  1. 更新 build.gradle 以使用 android gradle 插件版本 1.1.0-rc1 或更高版本(在 build.gradle 文件中手动或在文件 > 项目结构中的 UI 中手动)

  2. 向 app/build.gradle 添加必要的测试依赖项(见上文)。

  3. 在 Settings > Gradle > Experimental 中启用单元测试功能。

  4. 同步您的项目。

  5. 打开“构建变体”工具窗口(在左侧)并将测试工件更改为“单元测试”。

  6. 为您的测试源代码创建一个目录,即 src/test/java。您可以从命令行或使用“项目”工具窗口中的“项目”视图执行此操作。此时新目录应以绿色突出显示。注意:测试源目录的名称由 gradle 插件根据约定确定。

  7. 创建您的测试。您可以通过打开一个类,右键单击其名称并选择“转到 > 测试”来执行此操作。添加一些测试用例。
  8. 右键单击您的新测试类或方法,然后选择“运行...”。
  9. (可选)您可以直接使用 Gradle 来减少编译时间。为此,请转到“运行”菜单并选择“编辑配置”。在那里,找到默认的 JUnit 模板,删除启动前的“制作”步骤并添加一个“Gradle 感知制作”步骤(将任务名称留空)。

It is important to know that there are two test types: androidTestand plain test.

重要的是要知道有两种测试类型:androidTest和普通的test

  • androidTestis primarily for tests you run on an emulator or device, such as instrumentation tests. From the command line, you use ./gradlew connectedCheckto run these.
  • testis for tests you don't want to run on a device, such as the unit test you wrote. You run ./gradlew testto run these tests.
  • androidTest主要用于在模拟器或设备上运行的测试,例如仪器测试。从命令行,您./gradlew connectedCheck用来运行这些。
  • test用于您不想在设备上运行的测试,例如您编写的单元测试。您运行./gradlew test以运行这些测试。

As stated in the quote, you switch between androidTestand testin Android Studio by changing the test artifact.

如引用中所述,您可以通过更改测试工件在 Android StudioandroidTesttestAndroid Studio之间切换。

Naturally, it is preferred to not run tests on a device or emulator, since this speeds up the testing process a lot. With the new experimental unit test support, you gain access to stubbed Android API's without using a device. This lets you move more tests from androidTestto test.

当然,优选的是,一个设备或仿真器上不运行测试,因为这加速了测试过程很多。借助新的实验性单元测试支持,您无需使用设备即可访问存根 Android API。这使您可以将更多测试从 移动androidTesttest

回答by CommonSenseCode

For android studio 1.2 or greater, I include this answer since this is one of the first ranking at google and this is an excelent and VERY easy to follow tutorial on how to set unit tests with Android Studio, this is the link: https://io2015codelabs.appspot.com/codelabs/android-studio-testing#1

对于 android studio 1.2 或更高版本,我包含了这个答案,因为这是谷歌的第一个排名之一,这是一个关于如何使用 Android Studio 设置单元测试的优秀且非常容易遵循的教程,这是链接:https:/ /io2015codelabs.appspot.com/codelabs/android-studio-testing#1

After wasting 2 hours trying to run test I finally did it with the above link, hope it is as useful for you as for me.

在浪费了 2 个小时尝试运行测试之后,我终于用上面的链接完成了,希望它对你和我一样有用。

回答by Andrey

Nowadays Android Studio (current ver. 1.4) has full Unit test support without any workarounds. Just as suggested in the automatically generated ExampleUnitTest:

现在 Android Studio(当前版本 1.4)具有完整的单元测试支持,没有任何变通方法。正如自动生成的 ExampleUnitTest 中所建议的那样:

To work on unit tests, switch the Test Artifact in the Build Variants view.

To work on unit tests, switch the Test Artifact in the Build Variants view.

screen shot

截屏

回答by Yash

Go to settings then build tools then gradle and then experimental. In experimental uncheck enable all test artifacts. Thats it game over

转到设置,然后构建工具,然后是 gradle,然后是实验。在实验中取消选中启用所有测试工件。游戏结束