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'
}
由于