Android Studio简单unit testing不起作用

我正在尝试在AndroidStudio中做一个简单的unit testing,它不工作。 我已经尝试了很多教程,但直到现在还没有成功。

当我运行testing时,显示这个错误信息:

java.lang.RuntimeException: Method setUp in android.test.ActivityInstrumentationTestCase2 not mocked. 

我的testing课:

 public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> { public MainActivity activity; public MainActivityTest() { super(MainActivity.class); } @Before public void setUp() throws Exception { super.setUp(); activity = getActivity(); } @Test public void testApp() throws Exception { assertTrue(true); } @After public void tearDown() throws Exception { super.tearDown(); activity.finish(); } } 

MainActivity.class:

 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } 

的build.gradle(APP):

 apply plugin: 'com.android.application' android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { applicationId "com.helloworld.tripbudget" minSdkVersion 19 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:22.0.0' testCompile 'junit:junit:4.12' testCompile "org.mockito:mockito-core:1.+" compile files('libs/ormlite-android-4.49-SNAPSHOT.jar') compile files('libs/ormlite-core-4.49-SNAPSHOT.jar') } 

Solutions Collecting From Web of "Android Studio简单unit testing不起作用"

OP自己find了答案:

将下面的代码添加到build.gradle:

 android { // ... testOptions { unitTests.returnDefaultValues = true } } 

参考

我build议你使用JUnit4来testing你的活动:

 @RunWith(AndroidJUnit4.class) public final class MainActivityTest { @Rule public final ActivityRule<MainActivity> mainActivity = new ActivityRule<>(MainActivity.class); @Test public void testApp() { mainActivity.someFunction(); } } 

我build议不要使用Junit 4来扩展ActivityInstrumentationTestCase2。

有关示例,请参阅https://developer.android.com/training/testing/unit-testing/local-unit-tests.html

另外,对于嘲笑类Mockito已被certificate是非常有益的。

如果您需要模拟静态类,Power Mock可以很好地与Junit和Mockito配合使用https://github.com/jayway/powermock/wiki/GettingStarted

希望这可以帮助!