我试图在AndroidStudio中进行简单的单元测试,但它无法正常工作。我曾尝试过很多教程,但直到现在还没有成功。
当我运行测试时,会显示以下错误消息:
java.lang.RuntimeException: Method setUp in android.test.ActivityInstrumentationTestCase2 not mocked.
我的测试班:
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')
}
答案 0 :(得分:1)
将以下代码添加到build.gradle:
android { // ... testOptions { unitTests.returnDefaultValues = true } }
答案 1 :(得分:0)
我建议你使用JUnit4来测试你的活动:
@RunWith(AndroidJUnit4.class)
public final class MainActivityTest {
@Rule public final ActivityRule<MainActivity> mainActivity = new ActivityRule<>(MainActivity.class);
@Test
public void testApp() {
mainActivity.someFunction();
}
}
答案 2 :(得分:-3)
我建议不要使用Junit 4扩展ActivityInstrumentationTestCase2。
有关示例,请参阅https://developer.android.com/training/testing/unit-testing/local-unit-tests.html。
此外,对于模拟课程,Mockito已被证明是非常有益的。
如果你需要模拟静态类,Power Mock可以很好地使用Junit和Mockito https://github.com/jayway/powermock/wiki/GettingStarted。
希望这有帮助!