1
我已經使用robolectric和gradle-android-test-plugin設置了單元測試。我可以運行測試沒有問題,但我嘗試使用JSONOBJECT它失敗與「java.lang.RuntimeException:Stub!在org.json.JSONObject。(JSONObject.java:7)」錯誤。RuntimeException:存根!在JSONObject與Robolectric
這裏我的build.gradle文件
buildscript {
repositories {
mavenCentral()
maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:0.7.+'
classpath 'com.squareup.gradle:gradle-android-test-plugin:0.9.1-SNAPSHOT'
}
}
apply plugin: 'android'
apply plugin: 'android-test'
repositories {
mavenCentral()
maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
}
android {
compileSdkVersion 19
buildToolsVersion '19.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 19
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
sourceSets {
instrumentTest.setRoot('src/test')
}
}
dependencies {
compile 'com.android.support:support-v4:+'
compile files('libs/org.eclipse.paho.client.mqttv3.jar')
compile files('libs/volley.jar')
testCompile 'junit:junit:4.10'
testCompile 'org.robolectric:robolectric:2.3-SNAPSHOT'
testCompile 'com.squareup:fest-android:1.0.+'
instrumentTestCompile 'junit:junit:4.10'
instrumentTestCompile 'org.robolectric:robolectric:2.3-SNAPSHOT'
instrumentTestCompile 'com.squareup:fest-android:1.0.+'
}
我的Java代碼:
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import com.example.RobolectricGradleTestRunner;
@Config(emulateSdk = 18)
@RunWith(RobolectricGradleTestRunner.class)
public class VisitorChatTest {
JSONObject obj;
@BeforeClass
public void jsonTest() throws JSONException{
obj = new JSONObject("{ \"hello\" : \"test\"} ");
}
@Test
public void test() throws JSONException{
assertEquals(obj.getString("hello"), "test");
}
}
編輯:發現的錯誤!
代替實例中@BeforeClass所述的JSONObject的,被實例化在它@Before
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import com.example.RobolectricGradleTestRunner;
@Config(emulateSdk = 18)
@RunWith(RobolectricGradleTestRunner.class)
public class VisitorChatTest {
JSONObject obj;
@Before
public void jsonTest() throws JSONException{
obj = new JSONObject("{ \"hello\" : \"test\"} ");
}
@Test
public void test() throws JSONException{
assertEquals(obj.getString("hello"), "test");
}
}
類路徑沒有被設置爲@BeforeClass方框
學到了新東西!謝謝! – Shankar