本地测试和Instrumentation测试练习

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013144863/article/details/79959710

本篇讲解两个练习, 本地单元测试和Instrumentation测试.

练习: 创建本地单元测试

在接下来的练习中你将学到在Android 工程中如何创建一个简单的JUnit 4测试.

准备

在Android Studio 中创建一个Android工程, 并在app/build.gradle文件中添加JUnit 4依赖(参考上文).

创建测试

在你的 app/src/test 目录下创建如下面所示两个测试方法来测试ConverterUtil类

package com.lulu.androidtestdemo.androiduit;

import org.junit.Test;

import static junit.framework.Assert.assertEquals;

/**
 * Created by zhanglulu on 2018/2/24.
 */

public class ConverterUtilTest {
    @Test
    public void testConvertFahrenheitToCelsius() {
        float actual = ConverterUtil.convertCelsiusToFahrenheit(100);
        // expected value is 212
        float expected = 212;
        // use this method because float is not precise
        assertEquals("Conversion from celsius to fahrenheit failed", expected, actual, 0.001);
    }

    @Test
    public void testConvertCelsiusToFahrenheit() {
        float actual = ConverterUtil.convertFahrenheitToCelsius(212);
        // expected value is 100
        float expected = 100;
        // use this method because float is not precise
        assertEquals("Conversion from celsius to fahrenheit failed", expected, actual, 0.001);
    }
}

运行单元测试

通过运行相应的测试方法来确保单元测试正确执行,它们应该成功执行.

练习: Instrumentation 测试

这个练习使用到了模拟框架Mockito.请回顾之前Mock系列文章.

创建需要测试的类

添加以下工具类:

package com.lulu.androidtestdemo.instrumentation;

import android.content.Context;
import java.io.FileOutputStream;

/**
 * Created by zhanglulu on 2018/2/24.
 */
public class WriteConfigurationUtil {
    public static void writeConfiguration(Context ctx ) {
        try (FileOutputStream openFileOutput =
                     ctx.openFileOutput( "config.txt", Context.MODE_PRIVATE);) {

            openFileOutput.write("This is a test1.".getBytes());
            openFileOutput.write("This is a test2.".getBytes());
        } catch (Exception e) {
            // not handled
        }
    }
}

创建一个新的单元测试

编写一个单元测试来验证: openFileOutput()只被调用了一次,write()方法被调用了两次.

package com.lulu.androidtestdemo.instrumentation;

import android.content.Context;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

import java.io.FileOutputStream;

import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

/**
 * Created by zhanglulu on 2018/2/24.
 */
public class WriteConfigurationUtilTest {
    @Rule
    public MockitoRule rule = MockitoJUnit.rule();
    @Mock
    Context context;
    @Mock
    FileOutputStream fileOutputStream;
    @Test
    public void writeShouldWriteTwiceToFileSystem() {
        try {
            when(context.openFileOutput(anyString(), anyInt())).thenReturn(fileOutputStream);
            WriteConfigurationUtil.writeConfiguration(context);
            verify(context, times(1)).
                    openFileOutput(anyString(), anyInt());
            verify(fileOutputStream, atLeast(2)).write(any(byte[].class));

        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }
}

右击执行该测试.(测试执行通过)

敲行代码再睡觉

阅读更多

关于Instrumentation 测试如何测试OnFling()方法

05-11

rn我现在写了一个测试类继承了ActivityInstrumentationTestCase2, 我只能利用sendKeys()方法模拟手机键的输入模拟UI的按键的事件。可我希望能测试用户在屏幕上滑动组件的效果,如何模拟呢?是使用Instrumentation.sendPointerSync()这个方法来实现吗?rnrn我的测试方法如下:rnrnMonthModel currentMonth = activity.getCurrentMonth();rn final Instrumentation instrumentation = this.getInstrumentation();rn assertNotNull(instrumentation);rn long firstTime = SystemClock.uptimeMillis();rn final MotionEvent firstEvent = MotionEvent.obtain(firstTime, firstTime,rn MotionEvent.ACTION_DOWN, 100, 170, 0);rn long secondTime = SystemClock.uptimeMillis();rnrn final MotionEvent secondEvent = MotionEvent.obtain(secondTime,rn secondTime, MotionEvent.ACTION_UP, 100, 340, 0);rn activity.runOnUiThread(new Runnable() rnrn @Overridern public void run() rn // TODO Auto-generated method stubrn instrumentation.sendPointerSync(firstEvent);rn instrumentation.sendPointerSync(secondEvent);rn rnrn );rnrn currentMonth = currentMonth.gotoPreviousMonth();rn assertEquals(currentMonth, activity.getCurrentMonth());rnrn不考虑业务逻辑,当我执行这个方法的时候,会产生如下的异常:rnrnrnandroid.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.rnat android.view.ViewRoot.checkThread(ViewRoot.java:2802)rnat android.view.ViewRoot.requestLayout(ViewRoot.java:594)rnat android.view.View.requestLayout(View.java:8125)rnat android.view.View.setLayoutParams(View.java:4860)rnat android.view.WindowManagerImpl.updateViewLayout(WindowManagerImpl.java:188)rnat android.view.Window$LocalWindowManager.updateViewLayout(Window.java:428)rnat android.app.Activity.onWindowAttributesChanged(Activity.java:1974)rnat android.view.Window.setFlags(Window.java:638)rnat android.view.Window.addFlags(Window.java:603)rnat com.cybercom.canlendarApp.test.activity.CalendarAppTest.setUp(CalendarAppTest.java:37)rnat android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)rnat android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)rnat android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)rnat android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)rn希望有高手能为我解答疑惑,谢谢哈。

没有更多推荐了,返回首页