本地化的单元测试用的最多的就是Junit,在Java中,JUnit测试框架使用的是最流行和应用最广泛的,JUnit最新的版本是JUnit 4,该版本的测试用例编写起来更简单,运行效率更高。
下面就是一简单用例:
第一、配置
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'
compile 'com.android.support:appcompat-v7:23.1.1'
}
第二、在android studio的Build Variants的Test ArtiFact的模式调整为Unit Test。
第三、编写代码
public class Util {
public static int setTotal(int x,int y){
return x+y;
}
}
第四、编写测试用例
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
int total=Util.setTotal(10,9);
assertEquals(19,total);
}
}
上面只是一个简单的本地化的单元测试用例,但我们当前所面临的挑战是被测单元可能依赖于其他组件。而对于单元测试配置其他组件,绝对是过枉矫正。相反,我们可以使用Mocks框架代替其他组件,继续进行单元测试。mock译为“模拟”,所以该框架的核心就是如何模拟一个对象进行测试。
官网: http://mockito.org
API档:http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html
项目源码:https://github.com/mockito/mockito
下面官方有一个demo,该demo的功能就是对SharePreference的功能封装,能够保存一个java bean对象,所以代码结构包含两个类,SharedPreferenceEntry和SharedPreferencesHelper,而SharedPreferencesHelper若实现对象的存取,必须依赖SharePreference,所以我们需要模拟的对象就是SharePreference。
第一步:配置
android {
compileSdkVersion 23
buildToolsVersion '23.0.2'
defaultConfig {
applicationId "com.example.android.testing.unittesting.BasicSample"
minSdkVersion 8
versionCode 1
versionName "1.0"
targetSdkVersion 23
}
productFlavors {
}
}
dependencies {
// Unit testing dependencies.
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'
}
第二、在android studio的Build Variants的Test ArtiFact的模式调整为Unit Test。
第三、Java代码
SharedPreferenceEntry
public class SharedPreferenceEntry {
// Name of the user.
private final String mName;
// Date of Birth of the user.
private final Calendar mDateOfBirth;
// Email address of the user.
private final String mEmail;
public SharedPreferenceEntry(String name, Calendar dateOfBirth, String email) {
mName = name;
mDateOfBirth = dateOfBirth;
mEmail = email;
}
public String getName() {
return mName;
}
public Calendar getDateOfBirth() {
return mDateOfBirth;
}
public String getEmail() {
return mEmail;
}
}
SharedPreferencesHelper.java
public class SharedPreferencesHelper {
// Keys for saving values in SharedPreferences.
static final String KEY_NAME = "key_name";
static final String KEY_DOB = "key_dob_millis";
static final String KEY_EMAIL = "key_email";
// The injected SharedPreferences implementation to use for persistence.
private final SharedPreferences mSharedPreferences;
/**
* Constructor with dependency injection.
*
* @param sharedPreferences The {@link SharedPreferences} that will be used in this DAO.
*/
public SharedPreferencesHelper(SharedPreferences sharedPreferences) {
mSharedPreferences = sharedPreferences;
}
/**
* Saves the given {@link SharedPreferenceEntry} that contains the user's settings to
* {@link SharedPreferences}.
*
* @param sharedPreferenceEntry contains data to save to {@link SharedPreferences}.
* @return @{code true} if writing to {@link SharedPreferences} succeeded. @{code false}
* otherwise.
*/
public boolean savePersonalInfo(SharedPreferenceEntry sharedPreferenceEntry){
// Start a SharedPreferences transaction.
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(KEY_NAME, sharedPreferenceEntry.getName());
editor.putLong(KEY_DOB, sharedPreferenceEntry.getDateOfBirth().getTimeInMillis());
editor.putString(KEY_EMAIL, sharedPreferenceEntry.getEmail());
// Commit changes to SharedPreferences.
return editor.commit();
}
/**
* Retrieves the {@link SharedPreferenceEntry} containing the user's personal information from
* {@link SharedPreferences}.
*
* @return the Retrieved {@link SharedPreferenceEntry}.
*/
public SharedPreferenceEntry getPersonalInfo() {
// Get data from the SharedPreferences.
String name = mSharedPreferences.getString(KEY_NAME, "");
Long dobMillis =
mSharedPreferences.getLong(KEY_DOB, Calendar.getInstance().getTimeInMillis());
Calendar dateOfBirth = Calendar.getInstance();
dateOfBirth.setTimeInMillis(dobMillis);
String email = mSharedPreferences.getString(KEY_EMAIL, "");
// Create and fill a SharedPreferenceEntry model object.
return new SharedPreferenceEntry(name, dateOfBirth, email);
}
}
第四、测试用例
SharedPreferencesHelperTest.java
public class SharedPreferencesHelperTest {
private static final String TEST_NAME = "Test name";
private static final String TEST_EMAIL = "[email protected]";
private static final Calendar TEST_DATE_OF_BIRTH = Calendar.getInstance();
static {
TEST_DATE_OF_BIRTH.set(1980, 1, 1);
}
private SharedPreferenceEntry mSharedPreferenceEntry;
private SharedPreferencesHelper mMockSharedPreferencesHelper;
private SharedPreferencesHelper mMockBrokenSharedPreferencesHelper;
@Mock
SharedPreferences mMockSharedPreferences;
@Mock
SharedPreferences mMockBrokenSharedPreferences;
@Mock
SharedPreferences.Editor mMockEditor;
@Mock
SharedPreferences.Editor mMockBrokenEditor;
@Before
public void initMocks() {
// Create SharedPreferenceEntry to persist.
mSharedPreferenceEntry = new SharedPreferenceEntry(TEST_NAME, TEST_DATE_OF_BIRTH,
TEST_EMAIL);
// Create a mocked SharedPreferences.
mMockSharedPreferencesHelper = createMockSharedPreference();
// Create a mocked SharedPreferences that fails at saving data.
mMockBrokenSharedPreferencesHelper = createBrokenMockSharedPreference();
}
@Test
public void sharedPreferencesHelper_SaveAndReadPersonalInformation() {
// Save the personal information to SharedPreferences
boolean success = mMockSharedPreferencesHelper.savePersonalInfo(mSharedPreferenceEntry);
assertThat("Checking that SharedPreferenceEntry.save... returns true",
success, is(true));
// Read personal information from SharedPreferences
SharedPreferenceEntry savedSharedPreferenceEntry =
mMockSharedPreferencesHelper.getPersonalInfo();
// Make sure both written and retrieved personal information are equal.
assertThat("Checking that SharedPreferenceEntry.name has been persisted and read correctly",
mSharedPreferenceEntry.getName(),
is(equalTo(savedSharedPreferenceEntry.getName())));
assertThat("Checking that SharedPreferenceEntry.dateOfBirth has been persisted and read "
+ "correctly",
mSharedPreferenceEntry.getDateOfBirth(),
is(equalTo(savedSharedPreferenceEntry.getDateOfBirth())));
assertThat("Checking that SharedPreferenceEntry.email has been persisted and read "
+ "correctly",
mSharedPreferenceEntry.getEmail(),
is(equalTo(savedSharedPreferenceEntry.getEmail())));
}
@Test
public void sharedPreferencesHelper_SavePersonalInformationFailed_ReturnsFalse() {
// Read personal information from a broken SharedPreferencesHelper
boolean success =
mMockBrokenSharedPreferencesHelper.savePersonalInfo(mSharedPreferenceEntry);
assertThat("Makes sure writing to a broken SharedPreferencesHelper returns false", success,
is(false));
}
/**
* Creates a mocked SharedPreferences.
*/
private SharedPreferencesHelper createMockSharedPreference() {
// Mocking reading the SharedPreferences as if mMockSharedPreferences was previously written
// correctly.
when(mMockSharedPreferences.getString(eq(SharedPreferencesHelper.KEY_NAME), anyString()))
.thenReturn(mSharedPreferenceEntry.getName());
when(mMockSharedPreferences.getString(eq(SharedPreferencesHelper.KEY_EMAIL), anyString()))
.thenReturn(mSharedPreferenceEntry.getEmail());
when(mMockSharedPreferences.getLong(eq(SharedPreferencesHelper.KEY_DOB), anyLong()))
.thenReturn(mSharedPreferenceEntry.getDateOfBirth().getTimeInMillis());
// Mocking a successful commit.
when(mMockEditor.commit()).thenReturn(true);
// Return the MockEditor when requesting it.
when(mMockSharedPreferences.edit()).thenReturn(mMockEditor);
return new SharedPreferencesHelper(mMockSharedPreferences);
}
/**
* Creates a mocked SharedPreferences that fails when writing.
*/
private SharedPreferencesHelper createBrokenMockSharedPreference() {
// Mocking a commit that fails.
when(mMockBrokenEditor.commit()).thenReturn(false);
// Return the broken MockEditor when requesting it.
when(mMockBrokenSharedPreferences.edit()).thenReturn(mMockBrokenEditor);
return new SharedPreferencesHelper(mMockBrokenSharedPreferences);
}
}