1
我正嘗試在Android中爲我的數據庫類創建一個LOCAL JUNIT測試類。但是我遇到了一些問題。 這是測試類我想創建的示例:Android工作室中的Junit測試類
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import com.example.c.readit.model.Book;
import com.example.c.readit.model.VolumeInfo;
import com.example.c.readit.sqlite.SqliteHelper;
import org.junit.Test;
public class TestDB extends AndroidTestCase{
private SqliteHelper db;
@Override
public void setUp() throws Exception {
super.setUp();
RenamingDelegatingContext context = new RenamingDelegatingContext(getContext(), "test_");
db = new SqliteHelper(context);
}
@Override
public void tearDown() throws Exception {
db.close();
super.tearDown();
}
@Test
public void testSaveBook(){
String test_ID = "1234";
String test_TITLE = "TestBook";
String test_DESCRIPTION = "TestDescription";
String test_PUBLISHER = "TestPublisher";
String test_READ = "yes";
VolumeInfo testVolumeInfo = new VolumeInfo(test_TITLE,test_PUBLISHER,test_DESCRIPTION);
Book testBook = new Book(test_ID,testVolumeInfo,test_READ);
long wasSuccesful = db.saveBookMyBooks(testBook);
assertTrue(wasSuccesful != -1);
}
}
然而,一對夫婦的方法已被棄用(因爲API 24)。當在Android文檔中查看它們時,我可以看到我們應該使用「測試支持庫」(https://developer.android.com/topic/libraries/testing-support-library/index.html)。
我很難找到例子來學習如何使用它。當我找到一個工作示例時,我遇到了無法獲取SqlLite DB上下文的問題。如何獲取上下文 有些示例適用於插裝測試類,但我想寫一個當地的JUNIT測試班。
我的構建的gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.0"
defaultConfig {
applicationId "com.example.c.readit"
minSdkVersion 14
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
configurations.all {
// To fix 'Error:Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (24.0.0) and test app (23.0.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details.'
resolutionStrategy.force 'com.android.support:support-annotations:23.0.1'
}
testOptions {
unitTests.returnDefaultValues = true
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.android.support:design:24.0.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
compile 'com.android.support:recyclerview-v7:24.0.0'
androidTestCompile 'com.android.support.test:runner:0.4'
// Set this dependency to use JUnit 4 rules
androidTestCompile 'com.android.support.test:rules:0.4'
}
由於