【问题标题】:Unit testing in android studioandroid studio 中的单元测试
【发布时间】:2015-07-17 03:36:30
【问题描述】:

我正在使用最新版本的 android studio gradle 插件 1.2.3。我无法理解如何在其中创建单元测试;所有可用的答案都适用于旧版本的 android。帮帮我。

【问题讨论】:

  • 你搜索过吗?官方文档可能是?

标签: android-studio


【解决方案1】:

首先,您的单元测试需要不同的文件夹结构。 android studio 会自动为仪器测试生成 androidTest 文件夹,但您不能将单元测试放在那里。所以你必须创建一个“测试”文件夹:

- src
  -- androidTest //for instrumentation tests
  -- main        //source code
  -- test        //for unit tests

对您的测试使用与您要测试的类相同的包结构

您可以在 Android 仪器测试和单元测试之间切换您的 android studio 构建变体。

根据您选择的测试或 androidTest 文件夹将显示在您的项目选项卡中。

最后你必须在 gradle 中将 junit 添加到你的依赖项中:

dependencies {
  testCompile 'junit:junit:4.12'
}

您的测试文件夹中的测试类可以如下所示:

package package.of.class.to.test

import org.junit.Before;
import org.junit.Test;
...
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

public class TestSomething{

  @Before
  public void setup(){
    // test setup
  }

  @Test
  public void testSomething(){
    // your unit tests like these simple examples
    assertThat(anyBooleanResult, is(expectedBooleanResult));
    assertEquals(anyIntResult, expectedIntResult);
  }
}

有关更多信息,您还可以查看this thread

【讨论】:

  • 我正在使用带有插件 1.2.3 的 Android Studio 1.2.2 和 gradle 2.2.1。正如你所说,我之前曾尝试过,但在运行时显示“测试运行失败:无法找到仪器信息:ComponentInfo{com.user.test.myapplication.test/android.test.InstrumentationTestRunner} 并且因为它的新版本很少线程中提到的步骤不起作用:在 AS 中单击 java 类时,它不会显示“转到”来创建像 Eclipse 中那样的测试类。空测试套件。”
  • 你的单元测试是什么样的?看来您创建了一个仪器测试
  • 我更新了我的答案并为测试类添加了一个示例
  • 好的,所以 TestSomething 类不会扩展到任何东西
  • 不,没有必要为junit测试扩展一些东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多