我是Java,Android和JUnit的新手。我想学习如何为Android应用程序编写JUnit测试。为此,我有一个非常简单的Android应用程序(2个活动,2个按钮,每个按钮转到其他活动)。我想测试按钮。插入时,这个应用程序在我的手机上正常运行。我一直在查看SDK中提供的示例,我正在尝试模拟它们。
我的问题是,当我右键单击我的测试项目时,选择Run As - > Android JUnit测试,没有任何反应。我不知道为什么。
我的测试代码。
package com.example.twoactivities.test;
import android.app.Instrumentation.ActivityMonitor;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.SmallTest;
import android.widget.Button;
import com.example.twoactivities.MainActivity;
import com.example.twoactivities.MainActivity2;
public class ClickButton extends ActivityInstrumentationTestCase2<MainActivity> {
private Button mButton2;
private long TIMEOUT_IN_MS = 100000;
public ClickButton() {
super(MainActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
final MainActivity a = getActivity();
// ensure a valid handle to the activity has been returned
assertNotNull(a);
}
@SmallTest
public void click(){
// Set up an ActivityMonitor
ActivityMonitor activityMonitor = getInstrumentation().addMonitor(MainActivity2.class.getName(), null, false);
//check if button is enabled
assertTrue("button is enabled", mButton2.isEnabled());
//click button
mButton2.performClick();
MainActivity2 MainActivity2 = (MainActivity2) activityMonitor.waitForActivityWithTimeout(TIMEOUT_IN_MS );
assertNotNull("MainActivity2 is null", MainActivity2);
// assertEquals("Monitor for MainActivity2 has not been called", 1, activityMonitor.getHits());
// assertEquals("Activity is of wrong type", MainActivity2.class, MainActivity2.getClass());
// Remove the ActivityMonitor
getInstrumentation().removeMonitor(activityMonitor);
}
// public void tearDown() {
// }
}
(我知道这很简单,但我只是想把基础知识搞定。)
我的申请。
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void activity2(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity2.class);
startActivity(intent);
}
}
我的申请活动2。
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void activity1(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity.class);
startActivity(intent);
}
}
为什么我的测试类没有运行的任何想法?
谢谢, 斯蒂芬妮
答案 0 :(得分:0)
您必须右键单击测试本身,而不是项目。
根据documentation Android测试API支持JUnit 3代码样式,但不支持JUnit 4.尝试命名测试方法testClick