1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>JUnit FAQ</title>
<style type="text/css">
body {
font-style: normal;
font-weight: normal;
margin-left: 10pt;
margin-right: 10pt;
}
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.header {
color: black;
font-size: 125%;
font-weight: bold;
background: #33ff33;
padding-top: 2px;
padding-bottom: 2px;
padding-left: 5px;
margin-top: 25px;
}
.code {
background: white;
border-left: 5px solid #33ff33;
}
.code-red {
background: white;
border-left: 5px solid #cc0000;
}
</style>
</head>
<body>
<h1>
<font color="#33ff33">J</font><font color="#cc0000">U</font>nit FAQ
</h1>
<hr size="1"/>
<!--
Summary
-->
<p>
<i>
JUnit is an open source Java testing framework used to write and run
automated test.
<br/>
It is an instance of the xUnit architecture for unit
testing frameworks.
</i>
</p>
<hr size="1"/>
<p>
Editor: <a href="mailto:mike@clarkware.com">Mike Clark</a>,
<a href="http://www.clarkware.com">Clarkware Consulting</a>
</p>
<p>
Last modified on December 28, 2004
</p>
<hr/>
<!--
Table of Contents
-->
<div class="header">
Table of Contents
</div>
<ol>
<li>
<p>
<b><a href="#faqinfo">FAQ Info</a></b>
</p>
<ol>
<li><a href="#faqinfo_1">Who is responsible for this FAQ?</a></li>
<li><a href="#faqinfo_2">How can I contribute to this FAQ?</a></li>
<li><a href="#faqinfo_3">Where do I get the latest version of
this FAQ?</a></li>
</ol>
</li>
<li>
<p>
<b><a href="#overview">Overview</a></b>
</p>
<ol>
<li><a href="#overview_1">What is JUnit?</a></li>
<li><a href="#overview_2">Where is the JUnit home page?</a></li>
<li><a href="#overview_3">Where are the JUnit mailing lists and
forums?</a></li>
<li><a href="#overview_4">Where is the JUnit documentation?</a></li>
<li><a href="#overview_5">Where can I find articles on JUnit?</a></li>
<li><a href="#overview_6">What's the latest news on JUnit?</a></li>
<li><a href="#overview_7">How is JUnit licensed?</a></li>
<li><a href="#overview_8">What awards has JUnit won?</a></li>
</ol>
</li>
<li>
<p>
<b><a href="#started">Getting Started</a></b>
</p>
<ol>
<li><a href="#started_1">Where do I download JUnit?</a></li>
<li><a href="#started_2">How do I install JUnit?</a></li>
<li><a href="#started_3">How do I uninstall JUnit?</a></li>
<li><a href="#started_4">How do I ask questions?</a></li>
<li><a href="#started_5">How do I submit bugs, patches, or
feature requests?</a></li>
</ol>
</li>
<li>
<p>
<b><a href="#tests">Writing Tests</a></b>
</p>
<ol>
<li><a href="#tests_1">How do I write and run a simple test?</a></li>
<li><a href="#tests_2">How do I use a test fixture?</a></li>
<li><a href="#tests_3">Why isn't my test fixture being run?</a></li>
<li><a href="#tests_4">How do I test a method that doesn't
return anything?</a></li>
<li><a href="#tests_5">Under what conditions should I test get()
and set() methods?</a></li>
<li><a href="#tests_6">Under what conditions should I not test
get() and set() methods?</a></li>
<li><a href="#tests_7">How do I write a test that passes when an
expected exception is thrown?</a></li>
<li><a href="#tests_8">How do I write a test that fails when an
unexpected exception is thrown?</a></li>
<li><a href="#tests_9">What's the difference between a failure
and an error?</a></li>
<li><a href="#tests_10">How do I test protected methods?</a></li>
<li><a href="#tests_11">How do I test private methods?</a></li>
<li><a href="#tests_12">Why does JUnit only report the first
failure in a single test?</a></li>
<li><a href="#tests_13">In Java 1.4, 'assert' is a
keyword. Won't this conflict with JUnit's assert()
method?</a></li>
<li><a href="#tests_14">How do I test things that must be run in
a J2EE container (e.g. servlets, EJBs)?</a></li>
<li><a href="#tests_15">Do I need to write a TestCase class for
every class I need to test?</a></li>
<li><a href="#tests_16">Is there a basic template I can use to
create a test?</a></li>
<li><a href="#tests_17">How do I write a test for an abstract
class?</a></li>
<li><a href="#tests_18">When are tests garbage collected?</a></li>
</ol>
</li>
<li>
<p>
<b><a href="#organize">Organizing Tests</a></b>
</p>
<ol>
<li><a href="#organize_1">Where should I put my test files?</a></li>
<li><a href="#organize_2">How do I write a test suite for all of
my tests?</a></li>
<li><a href="#organize_3">How can I run setUp() and tearDown()
code once for all of my tests?</a></li>
</ol>
</li>
<li>
<p>
<b><a href="#running">Running Tests</a></b>
</p>
<ol>
<li><a href="#running_1">What CLASSPATH settings are needed to
run JUnit?</a></li>
<li><a href="#running_2">Why do I get a NoClassDefFoundError
when trying to test JUnit or run the samples?</a>
</li>
<li><a href="#running_3">How do I run the JUnit GUI test runner?</a>
</li>
<li><a href="#running_4">How do I run JUnit from my command window?</a>
</li>
<li><a href="#running_5">How do I run JUnit using Ant?</a>
</li>
<li><a href="#running_6">How do I use Ant to create HTML test reports?</a>
</li>
<li><a href="#running_7">How do I pass command-line arguments to a test execution?</a>
</li>
<li><a href="#running_8">Why do I get an error (ClassCastException or
LinkageError) using the GUI TestRunners?</a>
</li>
<li><a href="#running_9">Why do I get a LinkageError when using
XML interfaces in my TestCase?</a>
</li>
<li><a href="#running_10">Why do I get a ClassCastException when I
use narrow() in an EJB client TestCase?</a>
</li>
<li><a href="#running_11">Why do I get the warning "AssertionFailedError: No
tests found in XXX" when I run my test?</a>
</li>
<li><a href="#running_12">Why do I see "Unknown Source" in the stack trace of
a test failure, rather than the source file's line number?</a>
</li>
<li><a href="#running_13">Why does the "excluded.properties" trick not
work when running JUnit's GUI from inside my favorite IDE?</a>
</li>
<li><a href="#running_14">How do I get one test suite to invoke another?</a>
</li>
<li><a href="#running_15">How do I organize all test classes in a TestSuite
automatically and not use or manage a TestSuite explicitly?</a>
</li>
</ol>
</li>
<li>
<p>
<b><a href="#best">Best Practices</a></b>
</p>
<ol>
<li><a href="#best_1">When should tests be written?</a></li>
<li><a href="#best_2">Do I have to write a test for
everything?</a></li>
<li><a href="#best_3">How simple is 'too simple to break'?</a></li>
<li><a href="#best_4">How often should I run my tests?</a></li>
<li><a href="#best_5">What do I do when a defect is reported?</a></li>
<li><a href="#best_6">Why not just use System.out.println()?</a></li>
<li><a href="#best_7">Why not just use a debugger?</a></li>
</ol>
</li>
<li>
<p>
<b><a href="#extend">Extending JUnit</a></b>
</p>
<ol>
<li><a href="#extend_1">How do I extend JUnit?</a></li>
<li><a href="#extend_2">What kinds of extensions are
available?</a></li>
</ol>
</li>
<li>
<p>
<b><a href="#misc">Miscellaneous</a></b>
</p>
<ol>
<li><a href="#misc_1">How do I integrate JUnit with my IDE?</a></li>
<li><a href="#misc_2">How do I launch a debugger when a test
fails?</a></li>
<li><a href="#misc_3">Where can I find unit testing frameworks
similar to JUnit for other languages?</a></li>
</ol>
</li>
</ol>
<!--
FAQ Info
-->
<div class="header">
<a name="faqinfo">FAQ Info</a>
</div>
<ol>
<li>
<p>
<b><a name="faqinfo_1">Who is responsible for this FAQ?</a></b>
</p>
<p>
The current version of this FAQ is maintained by <a
href="mailto:mike@clarkware.com">Mike Clark</a>.
</p>
<p>
Most of the wisdom contained in this FAQ comes from the
collective insights and hard-won experiences of the many good
folks who participate on the JUnit mailing list and the JUnit
community at large.
</p>
<p>
If you see your genius represented anywhere in this FAQ without
due credit to you, please send me an email and I'll make things
right.
</p>
</li>
<li>
<p>
<b><a name="faqinfo_2">How can I contribute to this FAQ?</a></b>
</p>
<p>
Your contributions to this FAQ are greatly appreciated! The
JUnit community thanks you in advance.
</p>
<p>
To contribute to this FAQ, simply write a JUnit-related question
and answer, then send the unformatted text to <a
href="mailto:mike@clarkware.com">Mike Clark</a>. Corrections to
this FAQ are always appreciated, as well.
</p>
<p>
No reasonable contribution will be denied. Your name will
always appear along with any contribution you make.
</p>
</li>
<li>
<p>
<b><a name="faqinfo_3">Where do I get the latest version of this
FAQ?</a></b>
</p>
<p>
The master copy of this FAQ is available at <a
href="http://junit.sourceforge.net/doc/faq/faq.htm">http://junit.sourceforge.net/doc/faq/faq.htm</a>.
</p>
<p>
The JUnit distribution also includes this FAQ in
the <code>doc</code> directory.
</p>
</li>
</ol>
<!--
Overview
-->
<div class="header">
<a name="overview">Overview</a>
</div>
<ol>
<li>
<p>
<b><a name="overview_1">What is JUnit?</a></b>
</p>
<p>
JUnit is an open source Java testing framework used to write and
run repeatable tests. It is an instance of the xUnit
architecture for unit testing frameworks.
</p>
<p>
JUnit features include:
</p>
<ul>
<li>Assertions for testing expected results</li>
<li>Test fixtures for sharing common test data</li>
<li>Test suites for easily organizing and running tests</li>
<li>Graphical and textual test runners</li>
</ul>
<p>
JUnit was originally written by Erich Gamma and Kent Beck.
</p>
</li>
<li>
<p>
<b><a name="overview_2">Where is the JUnit home page?</a></b>
</p>
<p>
The official JUnit home page is <a
href="http://junit.org">http://junit.org</a>.
</p>
</li>
<li>
<p>
<b><a name="overview_3">Where are the JUnit mailing lists and
forums?</a></b>
</p>
<p>
There are 3 mailing lists dedicated to everything JUnit:
</p>
<ul>
<li>
<a
href="http://lists.sourceforge.net/lists/listinfo/junit-announce">JUnit
announcements</a>
</li>
<li>
<a href="http://groups.yahoo.com/group/junit/">JUnit user
list</a>
</li>
<li>
<a
href="http://lists.sourceforge.net/lists/listinfo/junit-devel">JUnit
developer list</a>
</li>
</ul>
<p>
You can <a
href="http://groups.yahoo.com/group/junit/">search</a> the JUnit
user list archives for answers to frequently asked questions not
included here.
</p>
<p>
There is also a <a
href="http://www.jguru.com/forums/home.jsp?topic=JUnit">jGuru
discussion forum</a> dedicated to everything JUnit.
</p>
</li>
<li>
<p>
<b><a name="overview_4">Where is the JUnit
documentation?</a></b>
</p>
<p>
The following documents are included in the JUnit distribution
in the <code>doc</code> directory:
</p>
<ul>
<li>
<a
href="http://junit.sourceforge.net/doc/testinfected/testing.htm">JUnit
Test Infected: Programmers Love Writing Tests</a>
</li>
<li>
<a href="http://junit.sourceforge.net/doc/cookbook/cookbook.htm">JUnit
Cookbook</a>
</li>
<li>
<a
href="http://junit.sourceforge.net/doc/cookstour/cookstour.htm">JUnit
- A Cook's Tour</a>
</li>
<li>
<a href="http://junit.sourceforge.net/doc/faq/faq.htm">JUnit
FAQ</a>
</li>
</ul>
</li>
<li>
<p>
<b><a name="overview_5">Where can I find articles on
JUnit?</a></b>
</p>
<p>
The JUnit home page maintains a list of <a
href="http://www.junit.org/news/article/index.htm">JUnit
articles</a>.
</p>
</li>
<li>
<p>
<b><a name="overview_6">What's the latest news on JUnit?</a></b>
</p>
<p>
The JUnit home page publishes the <a
href="http://www.junit.org/news/index.htm">latest JUnit
news</a>.
</p>
</li>
<li>
<p>
<b><a name="overview_7">How is JUnit licensed?</a></b>
</p>
<p>
JUnit is <a href="http://www.opensource.org/">Open Source
Software</a>, released under <a
href="http://oss.software.ibm.com/developerworks/oss/license-cpl.html">IBM's
Common Public License Version 0.5</a> and hosted on <a
href="http://sourceforge.net/projects/junit/">SourceForge</a>.
</p>
</li>
<li>
<p>
<b><a name="overview_8">What awards has JUnit won?</a></b>
</p>
<ul>
<li>
<p>
<a href="http://www.javaworld.com/javaworld/jw-03-2002/jw-0326-awards.html">2002 JavaWorld Editors' Choice Awards (ECA)</a>
</p>
<p>
Best Java Performance Monitoring/Testing Tool
</p>
</li>
<li>
<p>
<a
href="http://www.javaworld.com/javaworld/jw-06-2001/j1-01-awards.html">2001
JavaWorld Editors' Choice Awards (ECA)</a>
</p>
<p>
Best Java Performance Monitoring/Testing Tool
</p>
</li>
</ul>
</li>
</ol>
<!--
Getting Started
-->
<div class="header">
<a name="started">Getting Started</a>
</div>
<ol>
<li>
<p>
<b><a name="started_1">Where do I download JUnit?</a></b>
</p>
<p>
The latest version of JUnit is available on <a
href="http://sourceforge.net/project/showfiles.php?group_id=15278">SourceForge</a>.
</p>
</li>
<li>
<p>
<b><a name="started_2">How do I install JUnit?</a></b>
</p>
<ol>
<li>
<p>
First, <a
href="http://sourceforge.net/project/showfiles.php?group_id=15278">download</a>
the
latest version of JUnit, referred to below
as <code>junit.zip</code>.
</p>
</li>
<li>
<p>
Then install JUnit on your platform of choice:
</p>
<p>
<u>Windows</u>
</p>
<p>
To install JUnit on Windows, follow these steps:
</p>
<ol>
<li>
<p>
Unzip the <code>junit.zip</code> distribution file to
a directory referred to as <code>%JUNIT_HOME%</code>.
</p>
</li>
<li>Add JUnit to the classpath:
<p>
<code>set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar</code>
</p>
</li>
</ol>
<p>
<u>Unix (bash)</u>
</p>
<p>
To install JUnit on Unix, follow these steps:
</p>
<ol>
<li>
<p>
Unzip the <code>junit.zip</code> distribution file to
a directory referred to as <code>$JUNIT_HOME</code>.
</p>
</li>
<li>
<p>
Add JUnit to the classpath:
</p>
<p>
<code>export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit.jar</code>
</p>
</li>
</ol>
</li>
<li>
<p>
<i>(Optional)</i> Unzip
the <code>$JUNIT_HOME/src.jar</code> file.
</p>
</li>
<li>
<p>
Test the installation by using either the textual or
graphical test runner to run the sample tests distributed
with JUnit.
</p>
<p>
<i>Note: The sample tests are not contained in
the <code>junit.jar</code>, but in the installation
directory directly. Therefore, make sure that the JUnit
installation directory is in the CLASSPATH.</i>
</p>
<p>
For the textual TestRunner, type:
</p>
<div>
<blockquote><code>
java junit.textui.TestRunner junit.samples.AllTests
</code></blockquote>
</div>
<p>
For the graphical TestRunner, type:
</p>
<div>
<blockquote><code>
java junit.swingui.TestRunner junit.samples.AllTests
</code></blockquote>
</div>
<p>
All the tests should pass with an "OK" (textual) or a
green bar (graphical).
</p>
<p>
If the tests don't pass, verify
that <code>junit.jar</code> is in the CLASSPATH.
</p>
</li>
<li>
<p>
Finally, <a href="#overview_4">read</a> the documentation.
</p>
</li>
</ol>
</li>
<li>
<p>
<b><a name="started_3">How do I uninstall JUnit?</a></b>
</p>
<ol>
<li>
<p>
Delete the directory structure where you unzipped the JUnit
distribution.
</p>
</li>
<li>
<p>
Remove <code>junit.jar</code> from the classpath
</p>
</li>
</ol>
<p>
JUnit does not modify the registry so simply removing all the
files will fully uninstall it.
</p>
</li>
<li>
<p>
<b><a name="started_4">How do I ask questions?</a></b>
</p>
<p>
Questions that are not answered in the <a
href="http://junit.sourceforge.net/doc/faq/faq.htm">FAQ</a> or
in the <a href="#overview_4">documentation</a> should be posted
to the <a
href="http://www.jguru.com/forums/home.jsp?topic=JUnit">jGuru
discussion forum</a> or the <a
href="http://groups.yahoo.com/group/junit/">JUnit user mailing
list</a>.
</p>
<p>
Please stick to technical issues on the discussion forum and
mailing lists. Keep in mind that these are public, so
do <b>not</b> include any confidental information in your
questions!
</p>
<p>
You should also read <a
href="http://www.catb.org/~esr/faqs/smart-questions.html">"How
to ask questions the smart way"</a> by Eric Raymond before
participating in the discussion forum and mailing lists.
</p>
<p>
<i> NOTE:
<br/> Please do NOT submit bugs, patches, or feature requests
to the discussion forum or mailing lists. <br/> Refer instead
to <a href="#started_5">"How do I submit bugs, patches, or
feature requests?"</a>.
</i>
</p>
</li>
<li>
<p>
<b><a name="started_5">How do I submit bugs, patches, or
feature requests?</a></b>
</p>
<p>
JUnit celebrates programmers testing their own software. In this
spirit, bugs, patches, and feature requests that include JUnit
tests have a better chance of being addressed than those
without.
</p>
<p>
JUnit is forged on <a
href="http://sourceforge.net/projects/junit">SourceForge</a>.
Please use the tools provided by SourceForge for your
submissions.
</p>
</li>
</ol>
<!--
Writing Tests
-->
<div class="header">
<a name="tests">Writing Tests</a>
</div>
<ol>
<li>
<p>
<b><a name="tests_1"></a>How do I write and run a simple test?</b>
</p>
<ol>
<li>
<p>
Create a subclass of <code>TestCase</code>:
</p>
<div class="code">
<pre><code>
package junitfaq;
import java.util.*;
import junit.framework.*;
public class SimpleTest extends TestCase {
</code></pre>
</div>
</li>
<li>
<p>
Write a test method to assert expected results on the
object under test:
</p>
<div class="code">
<pre><code>
public void testEmptyCollection() {
Collection collection = new ArrayList();
assertTrue(collection.isEmpty());
}
</code></pre>
</div>
</li>
<li>
<p>
Write a <code>suite()</code> method that uses reflection
to dynamically create a test suite containing all
the <code>testXXX()</code> methods:
</p>
<div class="code">
<pre><code>
public static Test suite() {
return new TestSuite(SimpleTest.class);
}
</code></pre>
</div>
</li>
<li>
<p>
Write a <code>main()</code> method to conveniently run the
test with the textual test runner:
</p>
<div class="code">
<pre><code>
public static void main(String args[]) {
junit.textui.TestRunner.run(suite());
}
}
</code></pre>
</div>
</li>
<li>
<p>
Run the test:
</p>
<ul>
<li>
<p>
To run the test with the textual test runner used
in <code>main()</code>, type:
</p>
<div>
<blockquote><code>
java junitfaq.SimpleTest
</code></blockquote>
</div>
<p>
The passing test results in the following textual output:
</p>
<div>
<blockquote>
<pre><code>
.
Time: 0
OK (1 tests)
</code></pre>
</blockquote>
</div>
</li>
<li>
<p>
To run the test with the graphical test runner, type:
</p>
<div>
<blockquote><code>
java junit.swingui.TestRunner junitfaq.SimpleTest
</code></blockquote>
</div>
<p>
The passing test results in a green bar displayed in
the graphical UI.
</p>
</li>
</ul>
</li>
</ol>
</li>
<li>
<p>
<b><a name="tests_2"></a>How do I use a test fixture?</b>
</p>
<p>
A test fixture is useful if you have two or more tests for a
common set of objects. Using a test fixture avoids duplicating
the test code necessary to initialize and cleanup those common
objects for each test.
</p>
<p>
Tests can use the objects (variables) in a test fixture, with
each test invoking different methods on objects in the fixture
and asserting different expected results. Each test runs in its
own test fixture to isolate tests from the changes made by other
tests. That is, tests don't share the state of objects in the
test fixture. Because the tests are isolated, they can be run
in any order.
</p>
<p>
To create a test fixture, define a <code>setUp()</code> method
that initializes common objects and a <code>tearDown()</code>
method to cleanup those objects. The JUnit framework
automatically invokes the <code>setUp()</code> method before
each test is run and the <code>tearDown()</code> method after
each test is run.
</p>
<p>
The following test uses a test fixture to initialize and cleanup
a common <code>Collection</code> object such that both tests are
isolated from changes made by the other:
</p>
<div class="code">
<pre><code>
package junitfaq;
import junit.framework.*;
import java.util.*;
public class SimpleTest extends TestCase {
private Collection collection;
protected void setUp() {
collection = new ArrayList();
}
protected void tearDown() {
collection.clear();
}
public void testEmptyCollection() {
assertTrue(collection.isEmpty());
}
public void testOneItemCollection() {
collection.add("itemA");
assertEquals(1, collection.size());
}
}
</code></pre>
</div>
<p>
Given this test, the methods might execute in the following
order:
</p>
<div>
<blockquote>
<pre><code>
setUp()
testOneItemCollection()
tearDown()
setUp()
testEmptyCollection()
tearDown()
</code></pre>
</blockquote>
</div>
<p>
The ordering of test-method invocations is not guaranteed,
so <code>testEmptyCollection()</code> might be executed
before <code>testOneItemCollection()</code>. This is why the
test methods themselves must be written to be independent of one
another. What is guaranteed is that <code>setUp()</code> will
execute before each test method and <code>tearDown()</code> will
execute after each test method.
</p>
</li>
<li>
<p>
<b><a name="tests_3"></a>Why isn't my test fixture being run?</b>
</p>
<p>
Make sure the test fixture methods are defined as follows,
noting that both method names are case sensitive:
</p>
<div>
<blockquote><pre>
protected void setUp() {
// initialization code
}
protected void tearDown() {
// cleanup code
}
</pre></blockquote>
</div>
</li>
<li>
<p>
<b><a name="tests_4"></a>How do I test a method that doesn't
return anything?</b>
</p>
<p>
<i>(Submitted by: Dave Astels)</i>
</p>
<p>
Often if a method doesn't return a value, it will have some side
effect. Actually, if it doesn't return a value AND doesn't have
a side effect, it isn't doing anything.
</p>
<p>
There may be a way to verify that the side effect actually
occurred as expected. For example, consider
the <code>add()</code> method in the Collection classes. There
are ways of verifying that the side effect happened (i.e. the
object was added). You can check the size and assert that it is
what is expected:
</p>
<div class="code">
<pre><code>
public void testCollectionAdd() {
Collection collection = new ArrayList();
assertEquals(0, collection.size());
collection.add("itemA");
assertEquals(1, collection.size());
collection.add("itemB");
assertEquals(2, collection.size());
}
</code></pre>
</div>
<p>
Another approach is to make use of <a
href="http://www.mockobjects.com">MockObjects</a>.
</p>
<p>
A related issue is to design for testing. For example, if you
have a method that is meant to output to a file, don't pass in a
filename, or even a <code>FileWriter</code>. Instead, pass in
a <code>Writer</code>. That way you can pass in
a <code>StringWriter</code> to capture the output for testing
purposes. Then you can add a method
(e.g. <code>writeToFileNamed(String filename)</code>) to
encapsulate the <code>FileWriter</code> creation.
</p>
</li>
<li>
<p>
<b><a name="tests_5"></a>Under what conditions should I test
get() and set() methods?</b>
</p>
<p>
Unit tests are intended to alleviate fear that something might
break. If you think a <code>get()</code> or <code>set()</code>
method could reasonably break, or has in fact contributed to a
defect, then by all means write a test.
</p>
<p>
In short, test until you're confident. What you choose to test
is subjective, based on your experiences and confidence level.
Remember to be practical and maximize your testing investment.
</p>
<p>
Refer also to <a href="#best_3">"How simple is 'too simple to
break'?"</a>.
</p>
</li>
<li>
<p>
<b><a name="tests_6"></a>Under what conditions should I not test
get() and set() methods?</b>
</p>
<p>
<i>(Submitted by: J. B. Rainsberger)</i>
</p>
<p>
Most of the time, get/set methods just can't break, and if they
can't break, then why test them? While it is usually better to
test more, there is a definite curve of diminishing returns on
test effort versus "code coverage". Remember the maxim: "Test
until fear turns to boredom."
</p>
<p>
Assume that the <code>getX()</code> method only does "return x;"
and that the <code>setX()</code> method only does "this.x =
x;". If you write this test:
</p>
<div>
<blockquote><pre>
testGetSetX() {
setX(23);
assertEquals(23, getX());
}
</pre></blockquote>
</div>
<p>
then you are testing the equivalent of the following:
</p>
<div>
<blockquote><pre>
testGetSetX() {
x = 23;
assertEquals(23, x);
}
</pre></blockquote>
</div>
<p>
or, if you prefer,
</p>
<div>
<blockquote><pre>
testGetSetX() {
assertEquals(23, 23);
}
</pre></blockquote>
</div>
<p>
At this point, you are testing the Java compiler, or possibly
the interpreter, and not your component or application. There is
generally no need for you to do Java's testing for them.
</p>
<p>
If you are concerned about whether a property has already been
set at the point you wish to call <code>getX()</code>, then you
want to test the constructor, and not the <code>getX()</code>
method. This kind of test is especially useful if you have
multiple constructors:
</p>
<div>
<blockquote><pre>
testCreate() {
assertEquals(23, new MyClass(23).getX());
}
</pre></blockquote>
</div>
</li>
<li>
<p>
<b><a name="tests_7"></a>How do I write a test that passes when
an expected exception is thrown?</b>
</p>
<p>
Catch the exception within the test method. If it isn't thrown,
call the <code>fail()</code> method to signal the failure of the
test.
</p>
<p>
The following is an example test that passes when the
expected <code>IndexOutOfBoundsException</code> is raised:
</p>
<div class="code">
<pre><code>
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
try {
Object o = emptyList.get(0);
fail("Should raise an IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
assertTrue(true);
}
}
</code></pre>
</div>
</li>
<li>
<p>
<b><a name="tests_8"></a>How do I write a test that fails when
an unexpected exception is thrown?</b>
</p>
<p>
Declare the exception in the <code>throws</code> clause of the
test method and don't catch the exception within the test
method. Uncaught exceptions will cause the test to fail with an
error.
</p>
<p>
The following is an example test that fails when
the <code>IndexOutOfBoundsException</code> is raised:
</p>
<div class="code-red">
<pre><code>
public void testIndexOutOfBoundsExceptionNotRaised()
throws IndexOutOfBoundsException {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
</code></pre>
</div>
</li>
<li>
<p>
<b><a name="tests_9"></a>What's the difference between a failure
and an error?</b>
</p>
<p>
Assertions are used to check for the possibility of failures,
therefore failures are anticipated. Errors are unanticipated
problems resulting in uncaught exceptions being propagated from
a JUnit test method.
</p>
<p>
In the following example, the <code>FileNotFoundException</code>
is expected and checked with an assertion. If the expected
exception is not raised, then a failure is produced. If any
other unexpected <code>IOException</code> or unchecked exception
(e.g. <code>NullPointerException</code>) is raised, the JUnit
framework catches the exception and signals an error.
</p>
<div class="code">
<pre><code>
public void testNonexistentFileRead() throws IOException {
try {
File file = new File("doesNotExist.txt");
FileReader reader = new FileReader(file);
assertEquals('a', (char)reader.read());
fail("Read from a nonexistent file?!");
} catch (FileNotFoundException expected) {
assertTrue(true);
}
}
</code></pre>
</div>
<p>
In the following example, an <code>IOException</code> is not
expected. The JUnit framework will signal an error if
an <code>IOException</code>
(e.g. <code>FileNotFoundException</code>) or any unchecked
exception (e.g. <code>NullPointerException</code>) is raised.
</p>
<div class="code">
<pre><code>
public void testExistingFileRead() throws IOException {
// exists.txt created in setup(), perhaps
File file = new File("exists.txt");
FileReader reader = new FileReader(file);
assertEquals('a', (char)reader.read());
}
</code></pre>
</div>
<p>
Both failures and errors will cause the test to fail. However,
it is useful to differentiate between failures and errors
because the debugging process is slightly different.
</p>
<p>
In the first example, the use of <code>fail()</code> will not
generate a complete stack trace including the method that raised
the exception. In this case that's sufficient since we
anticipate that the exception will be raised. If it's not
raised, then it's a problem with the test itself.
</p>
<p>
In the second example, the JUnit framework catches the exception
and generates an error with a complete stack trace for the
exception. Since we don't expect this exception to be raised, a
complete stack trace is useful in debugging why it was raised.
</p>
</li>
<li>
<p>
<b><a name="tests_10"></a>How do I test protected methods?</b>
</p>
<p>
Place your tests in the same package as the classes under test.
</p>
<p>
Refer to <a href="#organize_1">"Where should I put my test
files?"</a> for examples of how to organize tests for protected
method access.
</p>
</li>
<li>
<p>
<b><a name="tests_11"></a>How do I test private methods?</b>
</p>
<p>
Testing private methods may be an indication that those methods
should be moved into another class to promote reusability.
</p>
<p>
But if you must...
</p>
<p>
You can use reflection to subvert the access control mechanism.
If you are using JDK 1.3 or higher you can use the <a
href="http://groups.yahoo.com/group/junit/files/src/PrivilegedAccessor.java">PrivilegedAccessor</a>
class. Examples of how to use this class are available in <a
href="http://groups.yahoo.com/group/junit/files/src/PrivilegedAccessorTest.java">PrivilegedAccessorTest</a>.
</p>
</li>
<li>
<p>
<b><a name="tests_12"></a>Why does JUnit only report the first
failure in a single test?</b>
</p>
<p>
<i>(Submitted by: J. B. Rainsberger)</i>
</p>
<p>
Reporting multiple failures in a single test is generally a sign
that the test does too much, compared to what a unit test ought
to do. Usually this means either that the test is really a
functional/acceptance/customer test or, if it is a unit test,
then it is too big a unit test.
</p>
<p>
JUnit is designed to work best with a number of small tests. It
executes each test within a separate instance of the test
class. It reports failure on each test. Shared setup code is
most natural when sharing between tests. This is a design
decision that permeates JUnit, and when you decide to report
multiple failures per test, you begin to fight against
JUnit. This is not recommended.
</p>
<p>
Long tests are a design smell and indicate the likelihood of a
design problem. Kent Beck is fond of saying in this case that
"there is an opportunity to learn something about your design."
We would like to see a pattern language develop around these
problems, but it has not yet been written down.
</p>
<p>
Finally, note that a single test with multiple assertions is
isomorphic to a test case with multiple tests:
</p>
<p>
One test method, three assertions:
</p>
<div>
<blockquote><pre><code>
public class MyTestCase extends TestCase {
public void testSomething() {
// Set up for the test, manipulating local variables
assertTrue(condition1);
assertTrue(condition2);
assertTrue(condition3);
}
}
</code></pre></blockquote>
</div>
<p>
Three test methods, one assertion each:
</p>
<div>
<blockquote><pre><code>
public class MyTestCase extends TestCase {
// Locale variables become instance variables
protected void setUp() {
// Set up for the test, manipulating instance variables
}
public void testCondition1() {
assertTrue(condition1);
}
public void testCondition2() {
assertTrue(condition2);
}
public void testCondition3() {
assertTrue(condition3);
}
}
</code></pre></blockquote>
</div>
<p>
The resulting tests use JUnit's natural execution and reporting
mechanism and, failure in one test does not affect the execution
of the other tests. You generally want exactly one test to fail
for any given bug, if you can manage it.
</p>
</li>
<li>
<p>
<b><a name="tests_13"></a>In Java 1.4, 'assert' is a
keyword. Won't this conflict
with JUnit's <code>assert()</code> method?</b>
</p>
<p>
<i>(Submitted by: David Stagner)</i>
</p>
<p>
JUnit 3.7 deprecated <code>assert()</code> and replaced it
with <code>assertTrue()</code>, which works exactly the same
way.
</p>
<p>
Simply upgrade your JUnit to version 3.7 or higher and change
all <code>assert()</code> calls in your existing tests
to <code>assertTrue()</code>.
</p>
</li>
<li>
<p>
<b><a name="tests_14"></a>How do I test things that must be run
in a J2EE container (e.g. servlets, EJBs)?</b>
</p>
<p>
Refactoring J2EE components to delegate functionality to other
objects that don't have to be run in a J2EE container will
improve the design and testability of the software.
</p>
<p>
<a href="http://jakarta.apache.org/cactus/index.html">Cactus</a>
is an open source JUnit extension that can be used to test J2EE
components in their natural environment.
</p>
</li>
<li>
<p>
<b><a name="tests_15"></a>Do I need to write
a <code>TestCase</code> class for every class I need to
test?</b>
</p>
<p>
<i>(Submitted by: J. B. Rainsberger)</i>
</p>
<p>
No. It is a convention to start with one <code>TestCase</code>
class per class under test, but it is not necessary.
</p>
<p>
<code>TestCase</code> classes only provide a way to organize
tests, nothing more. Generally you will start with
one <code>TestCase</code> class per class under test, but then
you may find that a small group of tests belong together with
their own common test fixture.[1] In this case, you may move
those tests to a new <code>TestCase</code> object. This is a
simple object-oriented refactoring: separating responsibilities
of an object that does too much.
</p>
<p>
Another point to consider is that the <code>TestSuite</code> is
the smallest execution unit in JUnit: you cannot execute
anything smaller than a TestSuite at one time without changing
source code. In this case, you probably do not want to put tests
in the same <code>TestCase</code> class unless they somehow
"belong together". If you have two groups of tests that you
think you'd like to execute separately from one another, it is
wise to place them in separate <code>TestCase</code> classes.
</p>
<p>
<i>
[1] A test fixture is a common set of test data and
collaborating objects shared by many tests. Generally they are
implemented as instance variables in the <code>TestCase</code>
class.
</i>
</p>
</li>
<li>
<p>
<b><a name="tests_16"></a>Is there a basic template I can use to
create a test?</b>
</p>
<p>
<i>(Submitted by: Eric Armstrong)</i>
</p>
<p>
The following templates are a good starting point. Copy/paste
and edit these templates to suit your coding style.
</p>
<p>
SampleTest is a basic test template:
</p>
<div>
<blockquote><pre><code>
import junit.framework.TestCase;
public class SampleTest extends TestCase {
private java.util.List emptyList;
/**
* Sets up the test fixture.
* (Called before every test case method.)
*/
protected void setUp() {
emptyList = new java.util.ArrayList();
}
/**
* Tears down the test fixture.
* (Called after every test case method.)
*/
protected void tearDown() {
emptyList = null;
}
public void testSomeBehavior() {
assertEquals("Empty list should have 0 elements", 0, emptyList.size());
}
public void testForException() {
try {
Object o = emptyList.get(0);
fail("Should raise an IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException success) {
}
}
public static void main(String args[]) {
junit.textui.TestRunner.run(SampleTest.class);
}
}
</code></pre></blockquote>
</div>
<p>
SampleTestSuite is a template for a suite of tests:
</p>
<div>
<blockquote><pre><code>
import junit.framework.Test;
import junit.framework.TestSuite;
public class SampleTestSuite {
public static Test suite() {
TestSuite suite = new TestSuite("Sample Tests");
//
// Add one entry for each test class
// or test suite.
//
suite.addTestSuite(SampleTest.class);
//
// For a master test suite, use this pattern.
// (Note that here, it's recursive!)
//
suite.addTest(AnotherTestSuite.suite());
return suite;
}
public static void main(String args[]) {
junit.textui.TestRunner.run(suite());
}
}
</code></pre></blockquote>
</div>
</li>
<li>
<p>
<b><a name="tests_17"></a>How do I write a test for an abstract
class?</b>
</p>
<p>
Refer to <a
href="http://c2.com/cgi/wiki?AbstractTestCases">http://c2.com/cgi/wiki?AbstractTestCases</a>.
</p>
</li>
<li>
<p>
<b><a name="tests_18"></a>When are tests garbage collected?</b>
</p>
<p>
<i>(Submitted by: Timothy Wall and Kent Beck)</i>
</p>
<p>
By design, the tree of Test instances is built in one pass, then
the tests are executed in a second pass. The test runner holds
strong references to all Test instances for the duration of the
test execution. This means that for a very long test run with
many Test instances, none of the tests may be garbage collected
until the end of the entire test run.
</p>
<p>
Therefore, if you allocate external or limited resources in a
test, you are responsible for freeing those resources.
Explicitly setting an object to <code>null</code> in
the <code>tearDown()</code> method, for example, allows it to be
garbage collected before the end of the entire test run.
</p>
</li>
</ol>
<!--
Organizing Tests
-->
<div class="header">
<a name="organize">Organizing Tests</a>
</div>
<ol>
<li>
<p>
<b><a name="organize_1"></a>Where should I put my test files?</b>
</p>
<p>
You can place your tests in the same package and directory as
the classes under test.
</p>
<p>
For example:
</p>
<div>
<blockquote><pre>
src
com
xyz
SomeClass.java
SomeClassTest.java
</pre></blockquote>
</div>
<p>
While adequate for small projects, many developers feel that
this approach clutters the source directory, and makes it hard
to package up client deliverables without also including
unwanted test code, or writing unnecessarily complex packaging
tasks.
</p>
<p>
An arguably better way is to place the tests in a separate
parallel directory structure with package alignment.
</p>
<p>
For example:
</p>
<div>
<blockquote><pre>
src
com
xyz
SomeClass.java
test
com
xyz
SomeClassTest.java
</pre></blockquote>
</div>
<p>
These approaches allow the tests to access to all the public and
package visible methods of the classes under test.
</p>
<p>
Some developers have argued in favor of putting the tests in a
sub-package of the classes under test (e.g. com.xyz.test). The
author of this FAQ sees no clear advantage to adopting this
approach and believes that said developers also put their curly
braces on the wrong line. :-)
</p>
</li>
<li>
<p>
<b><a name="organize_2"></a>How do I write a test suite for all
of my tests?</b>
</p>
<p>
Write a <code>suite()</code> method that creates
a <code>TestSuite</code> containing all your tests.
</p>
<p>
For example:
</p>
<div class="code">
<pre><code>
import junit.framework.*;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(SomeTest.suite());
suite.addTest(AnotherTest.suite());
return suite;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
}
</code></pre>
</div>
<p>
Running <code>AllTests</code> will automatically run all of its
contained tests in one fell swoop.
</p>
<p>
You can arbitrarily group any tests into test suites as
appropriate by package, logical layers, test type, etc.
</p>
</li>
<li>
<p>
<b><a name="organize_3"></a>How can I run setUp() and tearDown()
code once for all of my tests?</b>
</p>
<p>
The desire to do this is usually a symptom of excessive coupling
in your design. If two or more tests must share the same test
fixture state, then the tests may be trying to tell you that the
classes under test have some undesirable dependencies.
</p>
<p>
Refactoring the design to further decouple the classes under
test and eliminate code duplication is usually a better
investment than setting up a shared test fixture.
</p>
<p>
But if you must...
</p>
<p>
You can wrap the test suite containing all your tests in a
subclass of <code>TestSetup</code> which
invokes <code>setUp()</code> exactly once before all the tests
are run and invokes <code>tearDown()</code> exactly once after
all the tests have been run.
</p>
<p>
The following is an example <code>suite()</code> method that
uses a <code>TestSetup</code> for one-time initialization and
cleanup:
</p>
<div class="code">
<pre><code>
import junit.framework.*;
import junit.extensions.TestSetup;
public class AllTestsOneTimeSetup {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(SomeTest.suite());
suite.addTest(AnotherTest.suite());
TestSetup wrapper = new TestSetup(suite) {
protected void setUp() {
oneTimeSetUp();
}
protected void tearDown() {
oneTimeTearDown();
}
};
return wrapper;
}
public static void oneTimeSetUp() {
// one-time initialization code
}
public static void oneTimeTearDown() {
// one-time cleanup code
}
}
</code></pre>
</div>
</li>
</ol>
<!--
Running Tests
-->
<div class="header">
<a name="running">Running Tests</a>
</div>
<ol>
<li>
<p>
<b><a name="running_1"></a>What CLASSPATH settings are needed to
run JUnit?</b>
</p>
<p>
<i>(Submitted by: Eric Armstrong)</i>
</p>
<p>
To run your JUnit tests, you'll need the following elemements in
your CLASSPATH:
</p>
<ul>
<li>JUnit class files</li>
<li>Your class files, including your JUnit test classes</li>
<li>Libraries your class files depend on</li>
</ul>
<p>
If attempting to run your tests results in
a <code>NoClassDefFoundError</code>, then something is missing
from your CLASSPATH.
</p>
<p>
<u>Windows Example:</u>
</p>
<p>
<code>set
CLASSPATH=%JUNIT_HOME%\junit.jar;c:\myproject\classes;c:\myproject\lib\something.jar</code>
</p>
<p>
<u>Unix (bash) Example:</u>
</p>
<p>
<code>export CLASSPATH=$JUNIT_HOME/junit.jar:/myproject/classes:/myproject/lib/something.jar</code>
</p>
</li>
<li>
<p>
<b><a name="running_2"></a>Why do I get
a <code>NoClassDefFoundError</code> when trying to test JUnit
or run the samples?</b>
</p>
<p>
<i>(Submitted by: J.B. Rainsberger and Jason Rogers)</i>
</p>
<p>
Most likely your CLASSPATH doesn't include the JUnit
installation directory.
</p>
<p>
Refer to <a href="#running_1">"What CLASSPATH settings are
needed to run JUnit?"</a> for more guidance.
</p>
<p>
Also consider running <a
href="http://www.clarkware.com/software/WhichJUnit.zip">WhichJunit</a>
to print the absolute location of the JUnit class files required
to run and test JUnit and its samples.
</p>
<p>
If the CLASSPATH seems mysterious, read <a
href="http://java.sun.com/j2se/1.4/docs/tooldocs/findingclasses.html">this</a>!
</p>
</li>
<li>
<p>
<b><a name="running_3"></a>How do I run the JUnit GUI test runner?</b>
</p>
<p>
<i>(Submitted by: Eric Armstrong)</i>
</p>
<ol>
<li>
<p>
<a href="#running_1">Set your CLASSPATH</a>
</p>
</li>
<li>
<p>
Invoke the runner:
</p>
<p>
<code>
java junit.swingui.TestRunner <test class name>
</code>
</p>
</li>
</ol>
</li>
<li>
<p>
<b><a name="running_4"></a>How do I run JUnit from my command window?</b>
</p>
<p>
<i>(Submitted by: Eric Armstrong)</i>
</p>
<ol>
<li>
<p>
<a href="#running_1">Set your CLASSPATH</a>
</p>
</li>
<li>
<p>
Invoke the runner:
</p>
<p>
<code>
java junit.textui.TestRunner <test class name>
</code>
</p>
</li>
</ol>
</li>
<li>
<p>
<b><a name="running_5"></a>How do I run JUnit using Ant?</b>
</p>
<p>
<i>(Submitted by: Eric Armstrong)</i>
</p>
<ol>
<li>
<p>
Define any necessary Ant properties:
</p>
<div>
<pre><code>
<property name="src" value="./src" />
<property name="lib" value="./lib" />
<property name="classes" value="./classes" />
<property name="test.class.name" value="com.xyz.MyTestSuite" />
</code></pre>
</div>
</li>
<li>
<p>
Set up the CLASSPATH to be used by JUnit:
</p>
<div>
<pre><code>
<path id="test.classpath">
<pathelement location="${classes}" />
<pathelement location="/path/to/junit.jar" />
<fileset dir="${lib}">
<include name="**/*.jar"/>
</fileset>
</path>
</code></pre>
</div>
</li>
<li>
<p>
Define the Ant task for running JUnit:
</p>
<div>
<pre><code>
<target name="test">
<junit fork="yes" haltonfailure="yes">
<test name="${test.class.name}" />
<formatter type="plain" usefile="false" />
<classpath refid="test.classpath" />
</junit>
</target>
</code></pre>
</div>
</li>
<li>
<p>
Run the test:
</p>
<div>
<code>
ant test
</code>
</div>
</li>
</ol>
<p>
Refer to the <a
href="http://jakarta.apache.org/ant/manual/OptionalTasks/junit.html">JUnit
Ant Task</a> for more information.
</p>
</li>
<li>
<p>
<b><a name="running_6"></a>How do I use Ant to create HTML test
reports?</b>
</p>
<p>
<i>(Submitted by: Eric Armstrong and Steffen Gemkow)</i>
</p>
<ol>
<li>
<p>
Ensure that Ant's <code>optional.jar</code> file is either
in your CLASSPATH or exists in
your <code>$ANT_HOME/lib</code> directory.
</p>
</li>
<li>
<p>
Add an ANT property for the directory containing the HTML reports:
</p>
<div>
<code>
<property name="test.reports" value="./reports" />
</code>
</div>
</li>
<li>
<p>
Define the Ant task for running JUnit and generating reports:
</p>
<div>
<pre><code>
<target name="test-html">
<junit fork="yes" printsummary="no" haltonfailure="no">
<batchtest fork="yes" todir="${test.reports}" >
<fileset dir="${classes}">
<include name="**/*Test.class" />
</fileset>
</batchtest>
<formatter type="xml" />
<classpath refid="test.classpath" />
</junit>
<junitreport todir="${test.reports}">
<fileset dir="${test.reports}">
<include name="TEST-*.xml" />
</fileset>
<report todir="${test.reports}" />
</junitreport>
</target>
</code></pre>
</div>
</li>
<li>
<p>
Run the test:
</p>
<div>
<code>
ant test-html
</code>
</div>
</li>
</ol>
<p>
Refer to the
<a href="http://jakarta.apache.org/ant/manual/OptionalTasks/junit.html">JUnit Ant Task</a>
for more information.
</p>
</li>
<li>
<p>
<b><a name="running_7"></a>How do I pass command-line arguments
to a test execution?</b>
</p>
<p>
Use the <tt>-D</tt> JVM command-line options, as in:
</p>
<div>
<blockquote><code>
-DparameterName=parameterValue
</code></blockquote>
</div>
<p>
If the number of parameters on the command line gets unweildy,
pass in the location of a property file that defines a set of
parameters. Alternatively, the <a
href="http://junit-addons.sf.net">JUnit-addons package</a>
contains the <tt>XMLPropertyManager</tt>
and <tt>PropertyManager</tt> classes that allow you to define a
property file (or XML file) containing test parameters.
</p>
</li>
<li>
<p>
<b><a name="running_8"></a>Why do I get an error
(<code>ClassCastException</code> or
<code>LinkageError</code>) using the GUI TestRunners?</b>
</p>
<p>
<i>(Submitted by: Scott Stirling)</i>
</p>
<p>
JUnit's GUI TestRunners use a custom class loader
(<code>junit.runner.TestCaseClassLoader</code>) to dynamically
reload your code every time you press the "Run" button
so you don't have to restart the GUI to reload your classes if
you recompile them. The default classloaders of the Java Virtual
Machine do not dynamically reload changed classes. But
JUnit's custom class loader finds and loads classes from the
same CLASSPATH used by the JVM's system classloader. So, by
design, it "sits in front of" the system loader and
applies a filter to determine whether it should load a given
class or delegate the loading of a class to the system
classloader. This filter is configured with a list of String
patterns in a properties file
called <code>excluded.properties</code>.
</p>
<p>
The <code>excluded.properties</code> file contains a numbered
list
(<code>excluded.0</code>, <code>excluded.1</code>, <code>excluded.2</code>,
etc.) of properties whose values are patterns for packages. This
file is packaged in <code>junit.jar</code>
as <code>junit/runner/excluded.properties</code>. As of JUnit
3.7 and Java 1.4, its contents are:
</p>
<div>
<blockquote><pre>
#
# The list of excluded package paths for the TestCaseClassLoader
#
excluded.0=sun.*
excluded.1=com.sun.*
excluded.2=org.omg.*
excluded.3=javax.*
excluded.4=sunw.*
excluded.5=java.*
</pre></blockquote>
</div>
<p>
There are some conditions, discussed below, where the default
exclusions are insufficient and you will want to add some more
to this list and then either update the <code>junit.jar</code>
file with your customized version or place your customized
version in the CLASSPATH before <code>junit.jar</code>.
</p>
</li>
<li>
<p>
<b><a name="running_9"></a>Why do I get
a <code>LinkageError</code> when using
XML interfaces in my TestCase?</b>
</p>
<p>
<i>(Submitted by: Scott Stirling)</i>
</p>
<p>
The workaround as of JUnit 3.7 is to
add <code>org.w3c.dom.*</code> and <code>org.xml.sax.*</code> to
your <code>excluded.properties</code>.
</p>
<p>
It's just a matter of time before this fix becomes incorporated
into the released version of
JUnit's <code>excluded.properties</code>, since JAXP is a
standard part of JDK 1.4. It will be just like
excluding <code>org.omg.*</code>. By the way, if you download
the JUnit source from its Sourceforge CVS, you will find that
these patterns have already been added to the default
excluded.properties and so has a pattern for JINI. In fact, here
is the current version in CVS, which demonstrates how to add
exclusions to the list too:
</p>
<div>
<blockquote><pre>
#
# The list of excluded package paths for the TestCaseClassLoader
#
excluded.0=sun.*
excluded.1=com.sun.*
excluded.2=org.omg.*
excluded.3=javax.*
excluded.4=sunw.*
excluded.5=java.*
excluded.6=org.w3c.dom.*
excluded.7=org.xml.sax.*
excluded.8=net.jini.*
</pre></blockquote>
</div>
<p>
This is the most common case where the
default <code>excluded.properties</code> list needs
modification. The cause of the <code>LinkageError</code> is
related to using JAXP in your test cases. By JAXP I mean the
whole set of <code>javax.xml.*</code> classes and the
supporting <code>org.w3c.dom.*</code>
and <code>org.xml.sax.*</code> classes.
</p>
<p>
As stated above, the JUnit GUI TestRunners' classloader relies
on the <code>excluded.properties</code> for classes it should
delegate to the system classloader. JAXP is an unusual case
because it is a standard Java extension library dependent on
classes whose package names (<code>org.w3c.dom.*</code>
and <code>org.xml.sax.*</code>) do not begin with a standard
Java or Sun prefix. This is similar to the relationship
between <code>javax.rmi.*</code> and the <code>org.omg.*</code>
classes, which have been excluded by default in
JUnit'ss <code>excluded.properties</code> for a while.
</p>
<p>
What can happen, and frequently does when using the JUnit Swing
or AWT UI with test cases that reference, use or depend on JAXP
classes, such as Log4J, Apache SOAP, Axis, Cocoon, etc., is that
the JUnit class loader (properly)
delegates <code>javax.xml.*</code> classes it "sees"
to the system loader. But then the system loader, in the process
of initializing and loading that JAXP class, links and loads up
a bunch of <code>org.w3c.dom</code>/<code>org.xml.sax</code>
classes. When it does so, the JUnit custom classloader is not
involved at all because the system classloader never delegates
"down" or checks with custom classloaders to see if a
class is already loaded. At any point after this, if the JUnit
loader is asked to load
an <code>org.w3c.dom</code>/<code>org.xml.sax</code> class that
it's never seen before, it will try to load it because the
class' name doesn't match any of the patterns in the default
exclude list. That's when a <code>LinkageError</code>
occurs. This is really a flaw in the JUnit classloader design,
but there is the workaround given above.
</p>
<p>
Java 2 JVMs keep classes (remember, classes and objects, though
related, are different entities to the JVM - I'm talking
about classes here, not object instances) in namespaces,
identifying them by their fully qualified classname plus the
instance of their defining (not initiating) loader. The JVM will
attempt to assign all unloaded classes referenced by an already
defined and loaded class to that class's defining loader. The
JVM's classresolver routine (implemented as a C function in the
JVM source code) keeps track of all these class loading events
and "sees" if another classloader (such as the JUnit
custom loader) attempts to define a class that has already been
defined by the system loader. According to the rules of Java 2
loader constraints, in case a class has already been defined by
the system loader, any attempts to load a class should first be
delegated to the system loader. A "proper" way for
JUnit to handle this feature would be to load classes from a
repository other than the CLASSPATH that the system classloader
knows nothing about. And then the JUnit custom classloader could
follow the standard Java 2 delegation model, which is to always
delegate class loading to the system loader, and only attempt to
load if that fails. Since they both load from the CLASSPATH in
the current model, if the JUnit loader delegated like it's
supposed to, it would never get to load any classes since the
system loader would always find them.
</p>
<p>
You could try to hack around this in the JUnit source by
catching the <code>LinkageError</code> in
TestCaseClassLoader's <code>loadClass()</code> method and then
making a recovery call to <code>findSystemClass()</code> --
thereby delegating to the system loader after the violation has
been caught. But this hack only works some of the time, because
now you can have the reverse problem where the JUnit loader will
load a host of <code>org.w3c.dom</code>/<code>org.xml.sax</code>
classes, and then the system loader violates the loader
contraints at some point when it tries to do exactly what I
described above with JAXP because it doesn't ever delegate to
its logical child (the JUnit loader). Inevitably, if your test
cases use many JAXP and related XML classes, one or the other
classloader will end up violating the constraints whatever you
do.
</p>
</li>
<li>
<p>
<b><a name="running_10"></a>Why do I get
a <code>ClassCastException</code> when
I use <code>narrow()</code> in an EJB client TestCase?</b>
</p>
<p>
<i>(Submitted by: Scott Stirling)</i>
</p>
<p>
The solution is to prevent your EJB's interface classes from
being loaded by the JUnit custom class loader by adding them
to <code>excluded.properties</code>.
</p>
<p>
This is another problem inherent to JUnit's dynamically
reloading TestCaseClassLoader. Similar to the LinkageErrors
with JAXP and the <code>org.xml.sax</code>
and <code>org.w3c.dom</code> classes, but with a different
result.
</p>
<p>
Here's some example code:
</p>
<div>
<blockquote><pre>
Point point;
PointHome pointHome;
// The next line works in textui, but throws
// ClassCastException in swingui
pointHome = (PointHome)PortableRemoteObject.
narrow(ctx.lookup("base/PointHome"), PointHome.class);
</pre></blockquote>
</div>
<p>
When you call <code>InitialContext.lookup()</code>, it returns
an object that was loaded and defined by the JVM's system
classloader (<code>sun.misc.Launcher$AppClassLoader</code>), but
the <code>PointEJBHome.class</code> type is loaded by JUnit's
TestCaseClassLoader. In the <code>narrow()</code>, the two fully
qualified class names are the same, but the defining
classloaders for the two are different so you get the exception
during the narrow because the JVM doesn't see them as being the
same runtime class type.
</p>
<p>
Recall that in Java 2 an object's class (a.k.a. "runtime type")
is identified in the JVM as the pair of
<fully-qualified-classname;definingClassLoaderInstance> or
(in shorter form) <C;L>. That is, the defining loader's
identity is part of the runtime name identifying that class in
the JVM. Also recall that the JVM will expect a class's defining
loader to load all unloaded classes referenced by the classes it
loads.
</p>
<p>
If interested for debugging purposes, you can find out more
about which loader loaded which class by doing something like
this:
</p>
<div>
<blockquote><pre>
System.out.println(ctx.lookup("base/PointEJBHome").getClass().getClassLoader());
System.out.println(PointEJBHome.class.getClassLoader());
</pre></blockquote>
</div>
<p>
You'll find when using the GUI TestRunners that
the <code>PointEJBHome</code> type is defined by the JUnit
TestCaseClassLoader and the object returned
from <code>InitialContext.lookup()</code> was defined through
the JVM's system class loader. When using the tex-based
TestRunner they'll both have been loaded through the system
loader.
</p>
<p>
If you use Ant's <batchtest> task to run your test cases
and you have this problem, you can work around it by
setting <code>fork="true"</code>
on <code><batchtest></code>, which causes it to run each
test in its own Java Virtual Machine separate from Ant's
launching JVM.
</p>
<p>
For further reading about the principles of Java dynamic
classloading, the best resource is the short paper by Sheng
Liang, the architect of the Java 2 classloader architecture: <a
href="http://java.sun.com/people/sl/"><i>Dynamic Class Loading
in the Java Virtual Machine</i></a>, OOPSLA 1998.
</p>
</li>
<li>
<p>
<b><a name="running_11"></a>Why do I get the warning
"AssertionFailedError: No
tests found in XXX" when I run my test?</b>
</p>
<p>
Make sure the test contains one or more methods with names
beginning with "test".
</p>
<p>
For example:
</p>
<div>
<blockquote><pre>
public void testSomething() {
}
</pre></blockquote>
</div>
<p>
This error also commonly occurs when using
the <code>addTestSuite()</code> in an attempt to create a
hiearchy of test suites. For more information, see <a
href="#running_14">"How do I get one test suite to invoke
another?"</a>.
</p>
</li>
<li>
<p>
<b><a name="running_12"></a>Why do I see "Unknown Source" in the
stack trace of
a test failure, rather than the source file's line number?</b>
</p>
<p>
The debug option for the Java compiler must be enabled in order
to see source file and line number information in a stack trace.
</p>
<p>
When invoking the Java compiler from the command line, use
the <code>-g</code> option to generate all debugging info.
</p>
<p>
When invoking the Java compiler from an
<a href="http://jakarta.apache.org/ant/index.html">Ant</a> task, use the
<code>debug="on"</code> attribute. For example:
</p>
<div>
<blockquote><code>
<javac srcdir="${src}" destdir="${build}" debug="on" />
</code></blockquote>
</div>
<p>
When using older JVMs pre-Hotspot (JDK 1.1 and most/all 1.2),
run JUnit with the <code>-DJAVA_COMPILER=none</code> JMV command
line argument to prevent runtime JIT compilation from obscuring
line number info.
</p>
<p>
Compiling the test source with debug enabled will show the line
where the assertion failed. Compiling the non-test source with
debug enabled will show the line where an exception was raised
in the class under test.
</p>
</li>
<li>
<p>
<b><a name="running_13"></a>Why does the "excluded.properties"
trick not work when running JUnit's GUI from inside my
favorite IDE?</b>
</p>
<p>
<i>(Submitted by: William Pietri)</i>
</p>
<p>
Some IDEs come with a copy of JUnit, so your copy of JUnit in
the project classpath isn't the one being used. Replace
the <code>junit.jar</code> file used by the IDE with
a <code>junit.jar</code> file containing a
custom <code>excluded.properties</code> and your bar will once
again be green.
</p>
</li>
<li>
<p>
<b><a name="running_14"></a>How do I get one test suite to
invoke another?</b>
</p>
<p>
<i>(Submitted by: Eric Armstrong)</i>
</p>
<p>
To add a suite to a suite, use:
</p>
<div>
<blockquote><code>
suite.addTest(someOtherSuite.suite());
</code></blockquote>
</div>
</li>
<li>
<p>
<b><a name="running_15"></a>How do I organize all test classes
in a TestSuite automatically and not use or manage a TestSuite
explicitly?</b>
</p>
<p>
<i>(Submitted by: Bill de hora)</i>
</p>
<p>
There are a number of ways to do this:
</p>
<ol>
<li>
<p>
In Ant, use the <code>junit</code> task and
the <code>batchtest</code> element:
</p>
<div>
<pre><code>
<junit printsummary="yes" haltonfailure="yes">
...
<batchtest fork="yes">
<fileset dir="${src.dir}">
<include name="**/*Test.java" />
<include name="**/Test*.java" />
</fileset>
</batchtest>
</junit>
</code></pre>
</div>
<p>
Idiomatic naming patterns for unit tests
are <code>Test*.java</code> and <code>*Test.java</code>.
Documentation and examples are at <a
href="http://ant.apache.org/manual/OptionalTasks/junit.html">http://ant.apache.org/manual/OptionalTasks/junit.html</a>.
</p>
</li>
<li>
<p>
Use the <code>DirectorySuiteBuilder</code>
and <code>ArchiveSuiteBuilder</code> (for jar/zip files)
classes provided by JUnit-addons project:
</p>
<div>
<blockquote><pre>
DirectorySuiteBuilder builder = new DirectorySuiteBuilder();
builder.setSuffix("Test");
Test suite = builer.suite("/home/project/myproject/tests");
</pre></blockquote>
</div>
<p>
Documentation and examples are at <a
href="http://junit-addons.sourceforge.net/">http://junit-addons.sourceforge.net</a>.
</p>
</li>
<li>
<p>
Write your own custom suite builder.
</p>
<p>
Have your test classes implement an interface and write a
treewalker to load each class in a directory, inspect the
class, and add any classes that implement the interface to a
TestSuite.
</p>
<p>
You might only want to do this if you are <b>very</b>
uncomfortable with using a naming convention for test
classes. Aside from being slow for larger suites, ultimately
it's arguable whether it's more effort to follow a naming
convention that have test classes implement an interface!
</p>
<p>
An example of this approach is at
<a href="http://www.javaworld.com/javaworld/jw-12-2000/jw-1221-junit_p.html">http://www.javaworld.com/javaworld/jw-12-2000/jw-1221-junit_p.html</a>.
</p>
</li>
</ol>
</li>
</ol>
<!--
Best Practices
-->
<div class="header">
<a name="best">Best Practices</a>
</div>
<ol>
<li>
<p>
<b><a name="best_1"></a>When should tests be written?</b>
</p>
<p>
Tests should be written before the code. Test-first programming
is practiced by only writing new code when an automated test is
failing.
</p>
<p>
Good tests tell you how to best design the system for its
intended use. They effectively communicate in an executable
format how to use the software. They also prevent tendencies to
over-build the system based on speculation. When all the tests
pass, you know you're done!
</p>
<p>
Whenever a customer test fails or a bug is reported, first write
the necessary unit test(s) to expose the bug(s), <em>then</em>
fix them. This makes it almost impossible for that particular
bug to resurface later.
</p>
<p>
Test-driven development is a lot more fun than writing tests
after the code seems to be working. Give it a try!
</p>
</li>
<li>
<p>
<b><a name="best_2"></a>Do I have to write a test for
everything?</b>
</p>
<p>
No, just test everything that could reasonably break.
</p>
<p>
Be practical and maximize your testing investment. Remember
that investments in testing are equal investments in design. If
defects aren't being reported and your design responds well to
change, then you're probably testing enough. If you're spending
a lot of time fixing defects and your design is difficult to
grow, you should write more tests.
</p>
<p>
If something is difficult to test, it's usually an opportunity
for a design improvement. Look to improve the design so that
it's easier to test, and by doing so a better design will
usually emerge.
</p>
</li>
<li>
<p>
<b><a name="best_3"></a>How simple is 'too simple to break'?</b>
</p>
<p>
<i>(Submitted by: J. B. Rainsberger)</i>
</p>
<p>
The general philosophy is this: if it can't break <em>on its
own</em>, it's too simple to break.
</p>
<p>
First example is the <code>getX()</code> method. Suppose
the <code>getX()</code> method only answers the value of an
instance variable. In that case, <code>getX()</code> cannot
break unless either the compiler or the interpreter is also
broken. For that reason, don't test <code>getX()</code>; there
is no benefit. The same is true of the <code>setX()</code>
method, although if your <code>setX()</code> method does any
parameter validation or has any side effects, you likely need to
test it.
</p>
<p>
Next example: suppose you have written a method that does
nothing but forward parameters into a method called on another
object. That method is too simple to break.
</p>
<div>
<blockquote><pre>
public void myMethod(final int a, final String b) {
myCollaborator.anotherMethod(a, b);
}
</pre></blockquote>
</div>
<p>
<code>myMethod</code> cannot possibly break because it does nothing: it
forwards its input to another object and that's all.
</p>
<p>
The only precondition for this method is "myCollaborator !=
null", but that is generally the responsibility of the
constructor, and not of myMethod. If you are concerned, add a
test to verify that myCollaborator is always set to something
non-null by every constructor.
</p>
<p>
The only way myMethod could break would be
if <code>myCollaborator.anotherMethod()</code> were broken. In
that case, test <code>myCollaborator</code>, and not the current
class.
</p>
<p>
It is true that adding tests for even these simple methods
guards against the possibility that someone refactors and makes
the methods "not-so-simple" anymore. In that case, though, the
refactorer needs to be aware that the method is now complex
enough to break, and should write tests for it -- and preferably
before the refactoring.
</p>
<p>
Another example: suppose you have a JSP and, like a good
programmer, you have removed all business logic from it. All it
does is provide a layout for a number of JavaBeans and never
does anything that could change the value of any object. That
JSP is too simple to break, and since JSPs are notoriously
annoying to test, you should strive to make all your JSPs too
simple to break.
</p>
<p>
Here's the way testing goes:
</p>
<div>
<blockquote><pre>
becomeTimidAndTestEverything
while writingTheSameThingOverAndOverAgain
becomeMoreAggressive
writeFewerTests
writeTestsForMoreInterestingCases
if getBurnedByStupidDefect
feelStupid
becomeTimidAndTestEverything
end
end
</pre></blockquote>
</div>
<p>
The loop, as you can see, never terminates.
</p>
</li>
<li>
<p>
<b><a name="best_4"></a>How often should I run my tests?</b>
</p>
<p>
Run all your unit tests as often as possible, ideally every time
the code is changed. Make sure all your unit tests always run
at 100%. Frequent testing gives you confidence that your
changes didn't break anything and generally lowers the stress of
programming in the dark.
</p>
<p>
For larger systems, you may just run specific test suites that
are relevant to the code you're working on.
</p>
<p>
Run all your acceptance, integration, stress, and unit tests at
least once per day (or night).
</p>
</li>
<li>
<p>
<b><a name="best_5"></a>What do I do when a defect is reported?</b>
</p>
<p>
Test-driven development generally lowers the defect density of
software. But we're all fallible, so sometimes a defect will
slip through. When this happens, write a failing test that
exposes the defect. When the test passes, you know the defect
is fixed!
</p>
<p>
Don't forget to use this as a learning opportunity. Perhaps the
defect could have been prevented by being more aggressive about
testing everything that could reasonably break.
</p>
</li>
<li>
<p>
<b><a name="best_6"></a>Why not just use <code>System.out.println()</code>?</b>
</p>
<p>
Inserting debug statements into code is a low-tech method for
debugging it. It usually requires that output be scanned
manually every time the program is run to ensure that the code
is doing what's expected.
</p>
<p>
It generally takes less time in the long run to codify
expectations in the form of an automated JUnit test that retains
its value over time. If it's difficult to write a test to
assert expectations, the tests may be telling you that shorter
and more cohesive methods would improve your design.
</p>
</li>
<li>
<p>
<b><a name="best_7"></a>Why not just use a debugger?</b>
</p>
<p>
Debuggers are commonly used to step through code and inspect
that the variables along the way contain the expected values.
But stepping through a program in a debugger is a manual process
that requires tedious visual inspections. In essence, the
debugging session is nothing more than a manual check of
expected vs. actual results. Moreover, every time the program
changes we must manually step back through the program in the
debugger to ensure that nothing broke.
</p>
<p>
It generally takes less time to codify expectations in the form
of an automated JUnit test that retains its value over time. If
it's difficult to write a test to assert expected values, the
tests may be telling you that shorter and more cohesive methods
would improve your design.
</p>
</li>
</ol>
<!--
JUnit Extensions
-->
<div class="header">
<a name="extend">Extending JUnit</a>
</div>
<ol>
<li>
<p>
<b><a name="extend_1"></a>How do I extend JUnit?</b>
</p>
<p>
JUnit is a testing framework intended to be customized for
specialized use. Browsing the JUnit source code is an excellent
way to learn its design and discover how it can be extended.
</p>
<p>
Examples of JUnit extensions can be found in
the <code>junit.extensions</code> package:
</p>
<ul>
<li>
<code>TestDecorator</code>
<p>
A decorator for Tests. You can use it as the base class for
implementing new test decorators that add behavior before or
after a test is run.
</p>
</li>
<li>
<code>ActiveTestSuite</code>
<p>
A <code>TestSuite</code> that runs each test in a separate
thread and waits until all threads have terminated.
</p>
</li>
<li>
<code>TestSetup</code>
<p>
A <code>TestDecorator</code> to initialize and cleanup
test fixture state once before the test is run.
</p>
</li>
<li>
<code>RepeatedTest</code>
<p>
A <code>TestDecorator</code> that runs a test repeatedly.
</p>
</li>
<li>
<code>ExceptionTestCase</code>
<p>
A <code>TestCase</code> that expects a
particular <code>Exception</code> to be thrown.
</p>
<p>
Kent Beck has mentioned that <code>ExceptionTestCase</code>
likely does not provide enough to be useful; it is just as
easy to write the "exception test" yourself. Refer to the <a
href="#tests">"Writing Tests"</a> section for guidance.
</p>
</li>
</ul>
</li>
<li>
<p>
<b><a name="extend_2"></a>What kinds of extensions are available?</b>
</p>
<p>
The JUnit home page has a complete list of available <a
href="http://www.junit.org/news/extension/index.htm">JUnit
extensions</a>.
</p>
</li>
</ol>
<!--
Miscellaneous
-->
<div class="header">
<a name="misc">Miscellaneous</a>
</div>
<ol>
<li>
<p>
<b><a name="misc_1"></a>How do I integrate JUnit with my IDE?</b>
</p>
<p>
The JUnit home page maintains a list of <a
href="http://www.junit.org/news/ide/index.htm">IDE integration
instructions</a>.
</p>
</li>
<li>
<p>
<b><a name="misc_2"></a>How do I launch a debugger when a test fails?</b>
</p>
<p>
Start the <code>TestRunner</code> under the debugger and
configure the debugger so that it catches
the <code>junit.framework.AssertionFailedError</code>.
</p>
<p>
How you configure this depends on the debugger you prefer to
use. Most Java debuggers provide support to stop the program
when a specific exception is raised.
</p>
<p>
Notice that this will only launch the debugger when an expected
failure occurs.
</p>
</li>
<li>
<p>
<b><a name="misc_3"></a>Where can I find unit testing frameworks
similar to JUnit for other languages?</b>
</p>
<p>
XProgramming.com maintains a complete list of available <a
href="http://www.xprogramming.com/software.htm">xUnit testing
frameworks</a>.
</p>
</li>
</ol>
<br/>
<div align="right">
<a href="http://validator.w3.org/check?uri=referer">
<img src="http://www.w3.org/Icons/valid-xhtml10"
alt="Valid XHTML 1.0!" height="31" width="88" /></a>
</div>
</body>
</html>
|