在 android studio 中进行单元测试 [英] Unit testing in android studio

查看:47
本文介绍了在 android studio 中进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using newest version of android studio gradle plugin 1.2.3. I am unable to understand how to create unit tests in it; all the available answers are for older version of android. Help me.

推荐答案

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

first of all you need a different folder structure for your unit tests. android studio automatically generats the androidTest folder for instrumentation tests, but you can't put your unit tests in there. so you have to create a "test" folder:

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

为您的测试使用相同的包结构作为您要测试的类.

use the same package structure for your tests as for the class you want to test.

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

you can switch in your build variants of android studio between Android Instrumentation Tests and Unit Tests.

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

depending on your selection test or androidTest folder will be show in your project tab.

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

finally you have to add junit to your dependencies in gradle:

dependencies {
  testCompile 'junit:junit:4.12'
}

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

the test classes in your test folder can for example look like this:

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);
  }
}

有关更多信息,您还可以查看 这个话题.

for further information you can also take a look on this thread.

这篇关于在 android studio 中进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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