import junit.framework.TestCase; public class AdditionTest extends TestCase { PRivate int x = 1; private int y = 1; public void testAddition() { int z = x + y; assertEquals(2, z); } } 而在 JUnit 4 中,測試是由 @Test 注釋來識別的,如下所示:
import org.junit.Test; import junit.framework.TestCase; public class AdditionTest extends TestCase { private int x = 1; private int y = 1; @Test public void testAddition() { int z = x + y; assertEquals(2, z); } } 使用注釋的優點是不再需要將所有的方法命名為 testFoo()、testBar(),等等。例如,下面的方法也可以工作:
import org.junit.Test; import junit.framework.TestCase; public class AdditionTest extends TestCase { private int x = 1; private int y = 1; @Test public void additionTest() { int z = x + y; assertEquals(2, z); } } 下面這個方法也同樣能夠工作:
import org.junit.Test; import junit.framework.TestCase; public class AdditionTest extends TestCase { private int x = 1; private int y = 1; @Test public void addition() { int z = x + y; assertEquals(2, z); } } 這答應您遵循最適合您的應用程序的命名約定。例如,我介紹的一些例子采用的約定是,測試類對其測試方法使用與被測試的類相同的名稱。例如,List.contains() 由 ListTest.contains() 測試,List.add() 由 ListTest.addAll() 測試,等等。