博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在Android上实现Junit单元测试的四部曲
阅读量:4043 次
发布时间:2019-05-24

本文共 6355 字,大约阅读时间需要 21 分钟。

第一步:新建一个TestCase,记得要继承androidTestCase,才能有getContext()来获取当前的上下文变量,这在Android测试中很重要的,因为很多的Android api都需要context。

Java代码

    
public class TestMath extends AndroidTestCase {    
        
    private int i1;    
    private int i2;    
    static final String LOG_TAG = "MathTest";    
        
    @Override    
    protected void setUp() throws Exception {    
        i1 = 2;    
        i2 = 3;    
    }    
        
    public void testAdd() {    
        assertTrue("testAdd failed", ((i1 + i2) == 5));    
    }    
        
    public void testDec() {    
        assertTrue("testDec failed", ((i2 - i1) == 1));    
    }    
    
    @Override    
    protected void tearDown() throws Exception {    
        super.tearDown();    
    }    
    
    @Override    
    public void testAndroidTestCaseSetupProperly() {    
        super.testAndroidTestCaseSetupProperly();    
        //Log.d( LOG_TAG, "testAndroidTestCaseSetupProperly" );    
    }    
    
}    

第二步:新建一个TestSuit,这个就继承Junit的TestSuite就可以了,注意这里是用的addTestSuite方法,一开始使用addTest方法就是不能成功。

Java代码

    
public class ExampleSuite extends TestSuite {    
        
    public ExampleSuite() {    
        addTestSuite(TestMath.class);    
    }    
    
}    

第三步:新建一个Activity,用来启动单元测试,并显示测试结果。系统的AndroidTestRunner竟然什么连个UI界面也没有实现,这里只是最简单的实现了一个

Java代码

public class TestActivity extends Activity {     
        
    private TextView resultView;    
        
    private TextView barView;    
        
    private TextView messageView;    
        
    private Thread testRunnerThread;    
        
    private static final int SHOW_RESULT = 0;    
        
    private static final int ERROR_FIND = 1;    
    
    @Override    
    protected void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.main);    
        resultView = (TextView)findViewById(R.id.ResultView);    
        barView = (TextView)findViewById(R.id.BarView);    
        messageView = (TextView)findViewById(R.id.MessageView);    
        Button lunch = (Button)findViewById(R.id.LunchButton);    
        lunch.setOnClickListener(new View.OnClickListener() {    
            @Override    
            public void onClick(View v) {    
                startTest();    
            }    
        });    
    }    
        
    private void showMessage(String message) {    
        hander.sendMessage(hander.obtainMessage(ERROR_FIND, message));    
    }    
        
    private void showResult(String text) {    
        hander.sendMessage(hander.obtainMessage(SHOW_RESULT, text));    
    }    
        
    private synchronized void startTest() {    
        if (testRunnerThread != null    
                && testRunnerThread.isAlive()) {    
            testRunnerThread = null;    
        }    
        if (testRunnerThread == null) {    
            testRunnerThread = new Thread(new TestRunner(this));    
            testRunnerThread.start();    
        } else {    
            Toast.makeText(this,     
                    "Test is still running",     
                    Toast.LENGTH_SHORT).show();    
        }    
    }    
        
    public Handler hander = new Handler() {    
        public void handleMessage(Message msg) {    
            switch (msg.what) {    
                case SHOW_RESULT:    
                    resultView.setText(msg.obj.toString());    
                    break;    
                case ERROR_FIND:    
                    messageView.append(msg.obj.toString());    
                    barView.setBackgroundColor(Color.RED);    
                    break;    
                default:    
                    break;    
            }    
        }    
    };    
        
    class TestRunner implements Runnable, TestListener {    
        
        private Activity parentActivity;    
            
        private int testCount;    
            
        private int errorCount;    
            
        private int failureCount;    
            
        public TestRunner(Activity parentActivity) {    
            this.parentActivity = parentActivity;    
        }    
    
        @Override    
        public void run() {    
            testCount = 0;    
            errorCount = 0;    
            failureCount = 0;    
                
            ExampleSuite suite = new ExampleSuite();    
            AndroidTestRunner testRunner = new AndroidTestRunner();    
            testRunner.setTest(suite);    
            testRunner.addTestListener(this);    
            testRunner.setContext(parentActivity);    
            testRunner.runTest();    
        }    
    
        @Override    
        public void addError(Test test, Throwable t) {    
            errorCount++;    
            showMessage(t.getMessage() + "\n");    
        }    
    
        @Override    
        public void addFailure(Test test, AssertionFailedError t) {    
            failureCount++;    
            showMessage(t.getMessage() + "\n");    
        }    
    
        @Override    
        public void endTest(Test test) {    
            showResult(getResult());    
        }    
    
        @Override    
        public void startTest(Test test) {    
            testCount++;    
        }    
            
        private String getResult() {    
            int successCount = testCount - failureCount - errorCount;    
            return "Test:" + testCount + " Success:" + successCount + " Failed:" + failureCount + " Error:" + errorCount;    
        }    
            
    }    
    
}    

第四步:修改AndroidManifest.xml,加入,不然会提示找不到AndroidTestRunner,这里需要注意是这句话是放在applications下面的,我一开始也不知道,放错了地方,浪费了不少时间

Xml代码

xml version="1.0" encoding="utf-8"?>       
      
    
      
        
      
            
      
                
      
                
      
            intent-filter>      
        activity>      
    
      
    application>      
    
      
manifest>    

转载地址:http://xzgdi.baihongyu.com/

你可能感兴趣的文章
Node.js中的事件驱动编程详解
查看>>
mongodb 命令
查看>>
MongoDB基本使用
查看>>
mongodb管理与安全认证
查看>>
nodejs内存控制
查看>>
nodejs Stream使用中的陷阱
查看>>
MongoDB 数据文件备份与恢复
查看>>
数据库索引介绍及使用
查看>>
MongoDB数据库插入、更新和删除操作详解
查看>>
MongoDB文档(Document)全局唯一ID的设计思路
查看>>
mongoDB简介
查看>>
nodejs 浏览器弹窗下载图片 data:image/jpeg;base64示例
查看>>
JAVA实现AES加密
查看>>
JAVA实现DES加密
查看>>
关于AES256算法java端加密,ios端解密出现无法解密问题的解决方案
查看>>
node.js AES/ECB/PKCS5Padding 与其他语言的加密解密通用
查看>>
Java and Nodejs on AES
查看>>
AES加密CBC模式兼容互通四种编程语言平台【PHP、Javascript、Java、C#】
查看>>
js老生常谈之this,constructor ,prototype
查看>>
nodejs-post文件上传原理详解
查看>>