Android studio创建单元测试

在Android 项目开发中,需要对功能函数,api接口进行本地测试,于是需要android本地的测试,
首先,创建测试文件,在项目src目录下,创建androidtest,在这里插入图片描述
在Android项目中如下图
在这里插入图片描述
创建测试类,ExampleInstrumentedTest.java代码如下

package org.xmstring.www.wallet;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;

/**
 * Instrumented test, which will execute on an Android device.
 *
 * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {

    /**
     * 测试所用flag
     */
    private static final String testFlag = "wjltest";
    @Test
    public void useAppContext() throws Exception {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();

        assertEquals("org.xmstring.www.wallet", appContext.getPackageName());
    }
 }

在项目目录的文件夹中的build.gradle,增加测试包的依赖,

defaultConfig {
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

运行测试
在这里插入图片描述
测试结果

在这里插入图片描述
测试完成,采用Android本地测试,可以调用Android系统的api,但是相对测试速度比较慢。

猜你喜欢

转载自blog.csdn.net/w88193363/article/details/83824711
今日推荐