创建第一个单元测试
向类中添加一些基本的算术运算方法,比如加法和减法。将下列代码复制到编辑器中。不用担心实际的实现,暂时让所有的方法返回0。
1234567891011121314151617181920 | package com.example.testing.testingexample;public class { public double sum(double a, double b){ return 0; } public double substract(double a, double b){ return 0; } public double divide(double a, double b){ return 0; } public double multiply(double a, double b){ return 0; }} |
Android Studio提供了一个快速创建测试类的方法。只需在编辑器内右键点击Calculator类的声明,选择Go to > Test,然后“Create a new test…”
在打开的对话窗口中,选择JUnit4和”setUp/@Before“,同时为所有的计算器运算生成测试方法。
这样,就会在正确的文件夹内(app/src/test/java/com/example/testing/testingexample)
生成测试类框架,在框架内填入测试方法即可。下面是一个示例:
12345678910111213141516171819202122232425262728293031323334353637 | package com.example.testing.testingex 大专栏 AndroidStudio使用单元测试ample;import org.junit.Before;import org.junit.Test;import static org.junit.Assert.*;public class CalculatorTest { private Calculator mCalculator; public void setUp() throws Exception { mCalculator = new Calculator(); } @Test public void testSum() throws Exception { assertEquals(6d, mCalculator.sum(1d, 5d), 0); } @Test public void testSubstract() throws Exception { assertEquals(1d, mCalculator.substract(5d, 4d), 0); } @Test public void testDivide() throws Exception { assertEquals(4d, mCalculator.divide(20d, 5d), 0); } @Test public void testMultiply() throws Exception { assertEquals(10d, mCalculator.multiply(2d, 5d), 0); }} |
运行单元测试
右键点击CalculatorTest
类,选择Run > CalculatorTest。也可以通过命令行运行测试,在工程目录内输入:
1 | ./gradlew test |
无论如何运行测试,都应该看到输出显示4个测试都失败了。这是预期的结果,因为还没有实现运算操作。
修改Calculator类中的sum(double a, double b)
方法返回一个正确的结果,重新运行测试。你应该看到4个测试中的3个失败了。
123 | public double sum(double a, double b){ return a + b;} |
本文作者: Kyle
本文链接: https://zhutiankang.github.io
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 CN 许可协议。转载请注明出处!
来源:https://www.cnblogs.com/liuzhongrong/p/12361925.html