android如何单元测试handler发消息

Life is short , play more!
本文来自lihao's Blog,转载请注明。

我们要测试的apk程序, 有一个activity 用到了handler来进行消息的发送,那么我们如何来测试handler的消息发送呢?.


apk project 的 一个activity:

public class MainActivity extends Activity implements View.OnClickListener {

private Button button;

// 初始化handler
Handler hd = new Handler(){
@Override
public void handleMessage(Message msg) {

System.out.println(“self defined handle message, and his what value is: “+msg.what);
}
};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.test_text_id);

button = (Button)findViewById(R.id.test_button1_id);
button.setOnClickListener(this);
}

public void onClick(View v) {

sendMessage(v);
}

public void sendMessage(View v){

System.out.println(“star to call sendMessage”);
if(v==button) {
Message m = Message.obtain(hd,INCREMENT_PRO);
hd.sendMessage(m);

}
}
}

上述代码的功能描述:有一个按钮. 当点击后, 发送消息. handler的handleMessage 从消息队列里拿到消息, 并进行处理消息.

那么我们的测试工程,  test-projects 的代码可以这么写.

// 我们需要case继承ActivityInstrumentationTestCase2
public class MainActivityTest extends ActivityInstrumentationTestCase2 {

private Intent mStartIntent;
private MainActivity ma;
View v;
// 初始化测试代码里需要用得looper和handler
Looper myloop = Looper.myLooper();

Handler test = new Handler(myloop){

@Override
public void handleMessage(Message msg) {

System.out.println(“======= his what value is: “+msg.what);
}

};

public MainActivityTest() {

super( MainActivity.class);
}

public void testsendMessage() throws InterruptedException{

System.out.println(“start case********”);

ma = this.getActivity(); // start the activity

ma.hd = test;

v = (Button)ma.findViewById(R.id.test_button1_id);

test.sendMessage(Message.obtain(test,1));

Message m = Message.obtain(ma.hd,1);
ma.hd.sendMessage(m);
ma.sendMessage(v);

Thread.sleep(3000);
System.out.println(“##########” + ma.hd.obtainMessage().what);
}

protected void setUp() throws Exception {

super.setUp();
ma = getActivity();
assertNotNull(ma);

}

protected void tearDown() throws Exception {
super.tearDown();
}

}


发表评论

电子邮件地址不会被公开。 必填项已用*标注