比较好的参考资料
本文来源
assertThat(resultAdd, is(closeTo(2.222, 0.01)));
在Android project 被创建的过程中,会产生3类资源集:
在java文件夹中,有所有的资源集,单元测试资源在后缀有(test)的文件夹中,
比如com.android.example.SimpleCalc (test)
打开这个文件夹中的文件,可以看到测试文件:
- 在
import
包中没有Android frameworl classes ,仅有org.junit
,ori,hamcrest
,android.test
包。 - 在
@RunWirh(JUnit4.class)
声明中表示这是用的JUnit4
test.
@RunWith(JUnit4.class)
@SmallTest
public class CalculatorTest {
private Calculator mCalculator;
/**Set up the environment for testing **/
@Before
public void setUp() {
mCalculator = new Calculator(); }
/**Test for simple addition **/
@Test
public void addTwoNumbers() {
double resultAdd = mCalculator.add(1d, 1d);
assertThat(resultAdd, is(equalTo(2d)));
}
The
@RunWith
(JUnit4.class) annotation indicates the runner that will be used to run the tests in this class. A test runner is a library or set of tools that enables testing to occur and the results to be printed to a log. For tests with more complicated setup or infrastructure requirements (such as Espresso) you’ll use different test runners. For this example we’re using the basic JUnit4 test runner.
@SmallTest
表明在这个类中的所有测试都是单元测试,运行在毫秒级。
The
@SmallTest
annotation indicates that all the tests in this class are unit tests that have no dependencies, and run in milliseconds. The@SmallTest
,@MediumTest
, and@LargeTest
annotations are conventions that make it easier to bundle groups of tests into suites of similar functionality。
setUp()
方法时用于在测试前设置环境,包括@Before
声明
The
setUp()
method is used to set up the environment before testing, and includes the@Before
annotation. In this case the setup creates a new instance of theCalculator
class and assigns it to themCalculator
member variable.
addTwoNumbers()
方法是真是的测试,以@Test
开头
The addTwoNumbers() method is an actual test, and is annotated with @Test. Only methods in a test class that have an @Test annotation are considered tests to the test runner. Note that by convention test methods do not include the word “test.”
- 第一行
addTwoNumbers()
方法测试了add()
The first line of addTwoNumbers() calls the add() method from the Calculator class. You can only test methods that are public or package-protected. In this case the Calculator is a public class with public methods, so all is well.
- the assertion for the test 判定
The second line is the assertion for the test. Assertions are expressions that must evaluate and result in true for the test to pass. In this case the assertion is that the result you got from the add method (1 + 1) matches the given number 2. You’ll learn more about how to create assertions later in this practical.
添加测试可以通过编写@Test
来进行
比如:
@Test
public void addTwoNumbersNegative(){
double resultAdd = mCalculator.add(-1d,2d);
assertThat(resultAdd,is(equalTo(1d)));
}
@Test
public void addTwoNumbersFloats(){
double resultAdd = mCalculator.add(1.111f,1.111d);
assertThat(resultAdd, is(closeTo(2.222, 0.01)));
}
其中closeTo()
是近似等于,是测试更灵活,写时程序会出红色警告,双击它,然后按 ALT+ Enter 即可,成功后如下图