比較好的參考資料
本文來源
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 即可,成功後如下圖