Android测试用例-异步测试


     之前写测试用例一直是用AndroidTestCase,同步的测试跑的好好的

     后来发现测异步服务的时候总是一下子TestCase的进程就结束了,导致无法验证异步返回的数据。


后来经过排查,发现,很简单,测试用例不要继承AndroidTestCase,继承InstrumentationTestCase 就可以了,上代码


package com.haobao.wardrobe.test;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import android.test.InstrumentationTestCase;
import android.util.Log;

import com.haobao.wardrobe.io.HeaderTopicsHandler;
import com.haobao.wardrobe.io.WaterfallHandler;
import com.haobao.wardrobe.io.model.HeaderTopic;
import com.haobao.wardrobe.io.model.WaterFallItem;
import com.haobao.wardrobe.io.service.HomePageService;

public class HomeServiceTest extends InstrumentationTestCase{

	private static final String TAG = HomeServiceTest.class.getSimpleName();
	
	@Override
	protected void setUp() throws Exception {
		Log.v(TAG, "setUp");
	}

	@Override
	protected void tearDown() throws Exception {
		Log.v(TAG, "tearDown");
	}

	public void testHomeService() throws Throwable {
				final CountDownLatch signal = new CountDownLatch(2);
		runTestOnUiThread(new Runnable() {
			@Override
			public void run() {
				HomePageService.getInstance().loadWaterfall(20, new WaterfallHandler()
				{
					@Override
					public void onSuccess(
							ArrayList<WaterFallItem> waterFallItems) {
						Log.v(TAG, "WaterfallHandler onSuccess");
						for(WaterFallItem item : waterFallItems)
						{
							Log.v(TAG, "loadWaterfall item : " + item.id);
						}
					}

					@Override
					public void onFailure(Throwable error, String content) {
						Log.v(TAG, "loadWaterfall onFailure : " + error + "content : " + content);
					}
					
					@Override
					public void onFinish() {
						Log.v(TAG, "loadWaterfall onFinish");
						signal.countDown();
					}
				});
				
				HomePageService.getInstance().loadStarHeaderTopics(new HeaderTopicsHandler()
				{
					@Override
					public void onSuccess(ArrayList<HeaderTopic> headerTopics) {
						for(HeaderTopic header : headerTopics)
						{
							Log.v(TAG, "header :" + header.id);
						}
					}

					@Override
					public void onFailure(Throwable error, String content) {
						Log.v(TAG, "loadWaterfall onFailure : " + error + "content : " + content);
					}
					
					@Override
					public void onFinish() {
						Log.v(TAG, "loadWaterfall onFinish");
						signal.countDown();
					}
				});
			}
		});
		
		try {
			signal.await(30, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
		}
		Log.v(TAG, "HomeServiceTest Over");
	}

}



你可能感兴趣的:(Android测试用例-异步测试)