本地测试和Instrumentation测试练习
2018-04-14 本文已影响15人
changer0
本篇讲解两个练习, 本地单元测试和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();
}
}
}
敲行代码再睡觉右击执行该测试.(测试执行通过)