Android单元测试分为两种,一种是Junit test, 一种是InstrumentedTest,Junit test可直接称作单元测试,InstrumentedTest叫做设备化测试或者自动化测试。两种测试啥区别了?
简单地说,Junit test测试纯java代码的功能,InstrumentedTest测试对有Android代码的功能的测试,即,如果你的测试代码中有用到Android的某些lib,某些函数,那么就只能写到InstrumentedTest中。
例如,我要测试Zxing, ViewfinderView的shadeColor接口:
package com.google.zxing.view;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
import static org.junit.Assert.*;
@RunWith(AndroidJUnit4.class)
public class ViewfinderViewTest {
private ViewfinderView finderView;
@Before
public void setUp() throws Exception {
finderView = new ViewfinderView(getApplicationContext(), null);
}
@Test
public void shadeColor() {
int color = 0xFF3456;
color = finderView.shadeColor(color);
assertEquals(0x20FF3456, color);
color = 0x903456;
color = finderView.shadeColor(color);
assertEquals(0x20903456, color);
color = 0xF0903456;
color = finderView.shadeColor(color);
assertEquals(0x20903456, color);
}
}
ViewfinderView 继承自View,是Android的控件,即使shadeColor这个接口看起来是纯java代码,也只能写到InstrumentedTest中。
google的样例code:
https://github.com/android/testing-samples