Android Studio单元测试

Android Studio单元测试

介绍:之前对单元测试的概念一直很模糊,认为不是很重要,但是今天写工具的时候发现,对写好的代码测试很麻烦,不仅需要重新启动app,还需要管理好测试代码(防止和非测试部分混乱)。

as进行配置

1、点击下图小三角,选中“Edit C…”;
这里写图片描述
2、选中坐上角的”+”,选中“Android Test”;
3、对内部的参数配置,具体网络上搜索,点击“OK”;

创建代码

在工程中,创建类(main目录下面,在项目中需要用到),这里用Calculator做为例子,在里面添加加、减、乘、除的方法。
打开Calculator类,鼠标右键,选中”Go To”->”Test”,在弹出的框中选中“Create New Test…”;

Android Studio单元测试_第1张图片
完成后在test文件下面生成CalculatorTest类。填充实现的代码后,选中CalculatorTest,点击“Run Cac…”。

public class Calculator { public double sum(double a, double b){ return a+b; } public double substract(double a, double b){ return a-b; } public double divide(double a, double b){ return a/b; } public double multiply(double a, double b){ return a*b; } }
public class CalculatorTest { private Calculator mCalculator; @Before public void setUp() throws Exception { mCalculator = new Calculator(); } @Test public void testSum() throws Exception { assertEquals(6d, mCalculator.sum(1d, 5d), 0); } @Test public void testSubstract() throws Exception { assertEquals(1d, mCalculator.substract(5d, 4d), 0); } @Test public void testDivide() throws Exception { assertEquals(4d, mCalculator.divide(20d, 5d), 0); } @Test public void testMultiply() throws Exception { assertEquals(10d, mCalculator.multiply(2d, 5d), 0); } }

如果Calculator类中的方法有错误,那么android studio中底部有“Run”栏中,会提示错误。

现在需要研究的重点是UI的测试

  • 确保工程设置正确
dependencies {
    androidTestCompile 'com.android.support:support-annotations:23.0.1'
    androidTestCompile 'com.android.support.test:runner:0.4.1'
    androidTestCompile 'com.android.support.test:rules:0.4.1'
    // Optional -- Hamcrest library
    androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
    // Optional -- UI testing with Espresso
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
    // Optional -- UI testing with UI Automator
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'
}
android {
  defaultConfig {
  testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}

MainActivityText代码,位置在androidTest文件夹下面

public class MainActivityTest { private static final String STRING_TO_BE_TYPED = "Peter"; @Rule public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>( MainActivity.class); @Test public void testSayHello() throws Exception { onView(withId(R.id.editText)).perform(typeText(STRING_TO_BE_TYPED),closeSoftKeyboard()); String expectedText = "Hello, " + STRING_TO_BE_TYPED + "!"; } }

选中MainActivityTest,右击选中’Run Main…’,就可以看到效果。

参考文档

http://www.jianshu.com/p/03118c11c199
http://developer.android.com/intl/zh-cn/training/testing/start/index.html

你可能感兴趣的:(android,APP,AS)