代码参考:https://github.com/googlesamples/android-testing
解释参考:
https://www.jianshu.com/p/5732b4afd12f
官网教程:
https://developer.android.google.cn/training/testing/unit-testing/local-unit-tests#setup
看了很多单元测试,做起来都异常复杂。Instrumentation的一直没有做成功,放弃了。
2018年以后,testCompile这个配置改成了testImplementation,这里用的是最新版的,采用新版的配置。
一、junit
gradle添加依赖包:
testImplementation 'junit:junit:4.12'
在项目src/com...../test 目录下新建junit的用例:
public class EmailValidatorTest { @Test public void booleanTest() { boolean a = true; Assert.assertEquals(a,true); } }
二、Instrumentation 不会搞,网上的教程基本都是eclipse的,实在不知道是哪些依赖包,好像已经都失效了?
三、Robolectric的单元测试
添加gradle依赖:
testImplementation "org.robolectric:robolectric:3.6.1"
添加其他配置
android { // Robolectric testOptions { unitTests.includeAndroidResources = true } }
编写测试用例:
import android.content.Context; import androidx.test.core.app.ApplicationProvider; import org.junit.Test; import static com.google.common.truth.Truth.assertThat; public class UnitTestSampleJava { private static final String FAKE_STRING = "HELLO_WORLD"; private Context context = ApplicationProvider.getApplicationContext(); @Test public void readStringFromContext_LocalizedString() { // Given a Context object retrieved from Robolectric... ClassUnderTest myObjectUnderTest = new ClassUnderTest(context); // ...when the string is returned from the object under test... String result = myObjectUnderTest.getHelloWorldString(); // ...then the result should be the expected one. assertThat(result).isEqualTo(FAKE_STRING); } }
四、Mockito
添加gradle依赖:
// Optional -- Mockito framework testImplementation 'org.mockito:mockito-core:1.10.19' //mockito androidTestImplementation 'org.mockito:mockito-core:1.10.19'
编写用例
import android.content.Context; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class UnitTestSample { private static final String FAKE_STRING = "HELLO WORLD"; @Mock Context mockContext; @Test public void readStringFromContext_LocalizedString() { // Given a mocked Context injected into the object under test... when(mockContext.getString(R.string.hello_world)) .thenReturn(FAKE_STRING); ClassUnderTest myObjectUnderTest = new ClassUnderTest(mockContext); // ...when the string is returned from the object under test... String result = myObjectUnderTest.getHelloWorldString(); // ...then the result should be the expected one. assertThat(result, is(FAKE_STRING)); } }