结合junit + ant + emma实现Android项目单元测试代码覆盖率统计
1.建立一个简单的android应用
应用的界面如下,首先是两个id分别为value1和value2的输入框用于输入两个数字,然后是两个按钮,分别用来实现两个数的求和与求积操作,运算的结果在id为result的文本框中显示。
整个应用只有一个Activity,主要代码如下:
public class MainActivity extends Activity { protected static final String LOG_TAG = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText value1 = (EditText) findViewById(R.id.value1); final EditText value2 = (EditText) findViewById(R.id.value2); final EditText result = (EditText) findViewById(R.id.result); Button addButton = (Button) findViewById(R.id.addValues); addButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { int val1 = Integer.parseInt(value1.getText().toString()); int val2 = Integer.parseInt(value2.getText().toString()); Integer answer = val1 + val2; result.setText(answer.toString()); } catch (Exception e) { Log.e(LOG_TAG, "Failed to add numbers", e); } } }); Button multiplyButton = (Button) findViewById(R.id.multiplyValues); multiplyButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { int val1 = Integer.parseInt(value1.getText().toString()); int val2 = Integer.parseInt(value2.getText().toString()); Integer answer = val1 * val2; result.setText(answer.toString()); } catch (Exception e) { Log.e(LOG_TAG, "Failed to multiply numbers", e); } } }); } |
2.利用JUnit基于android的扩展,从eclipse中生成应用项目对应的测试项目
右击Demo项目名称,在弹出的菜单中依次选择Android->New Test Project,如图:
在弹出的对话框中进行设置,如下:
设置对应于Demo项目的测试项目名为:DemoTest
选择测试对象为Demo项目:
随后得到了针对Demo项目的基于JUnit在android上的扩展的单元测试框架:
3.在测试项目中编写测试用例
首先在com.winston.demo.test包中新建一个测试用例,操作如下:
测试用例的设置如下: