testing.html 540.2 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
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 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Testing | Spring Docs</title>
    <meta name="generator" content="VuePress 1.9.7">
    <link rel="icon" type="image/png" sizes="16x16" href="/images/icons/favicon.ico">
    <link rel="icon" type="image/png" sizes="48x48" href="/images/icons/icon-48x48.png">
    <link rel="icon" type="image/png" sizes="72x72" href="/images/icons/icon-72x72.png">
    <link rel="manifest" href="/manifest.webmanifest">
    <link rel="apple-touch-icon" href="/images/icons/icon_48x48.png">
    <link rel="mask-icon" href="/images/icons/favicon.ico" color="#5dac38">
    <script>
    var _hmt = _hmt || [];
    (function () {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?8eefd6b163dcb3f5762af6b0825e2dd1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
    </script>
    <meta name="description" content="This chapter covers Spring’s support for integration testing and best practices for unit
testing. The Spring team advocates test-driven development (TDD). The Spring team has
found that the correct use of inversion of control (IoC) certainly does make both unit
and integration testing easier (in that the presence of setter methods and appropriate
constructors on classes makes them easier to wire together in a test without having to
set up service locator registries and similar structures).">
    <meta name="twitter:title" content="Testing">
    <meta name="twitter:description" content="This chapter covers Spring’s support for integration testing and best practices for unit
testing. The Spring team advocates test-driven development (TDD). The Spring team has
found that the correct use of inversion of control (IoC) certainly does make both unit
and integration testing easier (in that the presence of setter methods and appropriate
constructors on classes makes them easier to wire together in a test without having to
set up service locator registries and similar structures).">
    <meta name="twitter:card" content="summary">
    <meta name="twitter:url" content="https://spring.gitcode.net/en/spring-framework/testing.html">
    <meta property="og:type" content="article">
    <meta property="og:title" content="Testing">
    <meta property="og:description" content="This chapter covers Spring’s support for integration testing and best practices for unit
testing. The Spring team advocates test-driven development (TDD). The Spring team has
found that the correct use of inversion of control (IoC) certainly does make both unit
and integration testing easier (in that the presence of setter methods and appropriate
constructors on classes makes them easier to wire together in a test without having to
set up service locator registries and similar structures).">
    <meta property="og:url" content="https://spring.gitcode.net/en/spring-framework/testing.html">
    <meta property="og:site_name" content="Spring 中文文档社区">
    <meta itemprop="name" content="Testing">
    <meta itemprop="description" content="This chapter covers Spring’s support for integration testing and best practices for unit
testing. The Spring team advocates test-driven development (TDD). The Spring team has
found that the correct use of inversion of control (IoC) certainly does make both unit
and integration testing easier (in that the presence of setter methods and appropriate
constructors on classes makes them easier to wire together in a test without having to
set up service locator registries and similar structures).">
    <meta name="application-name" content="Spring 中文文档社区">
    <meta name="apple-mobile-web-app-title" content="Spring 中文社区">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="msapplication-TileColor" content="#5dac38">
    <meta name="theme-color" content="#5dac38">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="baidu-site-verification" content="code-tApgxyb9G8">
    
    <link rel="preload" href="/assets/css/0.styles.af3770e9.css" as="style"><link rel="preload" href="/assets/js/app.cf11b18e.js" as="script"><link rel="preload" href="/assets/js/3.50918073.js" as="script"><link rel="preload" href="/assets/js/4.cd4c3ff4.js" as="script"><link rel="preload" href="/assets/js/99.513483d0.js" as="script"><link rel="prefetch" href="/assets/js/10.675f4d7e.js"><link rel="prefetch" href="/assets/js/100.89ddf0f9.js"><link rel="prefetch" href="/assets/js/101.a2584c55.js"><link rel="prefetch" href="/assets/js/102.53225958.js"><link rel="prefetch" href="/assets/js/103.be06048d.js"><link rel="prefetch" href="/assets/js/104.a2328e06.js"><link rel="prefetch" href="/assets/js/105.78529341.js"><link rel="prefetch" href="/assets/js/106.fc779386.js"><link rel="prefetch" href="/assets/js/107.375c8dec.js"><link rel="prefetch" href="/assets/js/108.cf4ca7e2.js"><link rel="prefetch" href="/assets/js/109.f4d3964d.js"><link rel="prefetch" href="/assets/js/11.b58e279a.js"><link rel="prefetch" href="/assets/js/110.4ae56c4d.js"><link rel="prefetch" href="/assets/js/111.baf7121d.js"><link rel="prefetch" href="/assets/js/112.a963ade8.js"><link rel="prefetch" href="/assets/js/113.edbb458c.js"><link rel="prefetch" href="/assets/js/114.7e2b354f.js"><link rel="prefetch" href="/assets/js/115.4e41285c.js"><link rel="prefetch" href="/assets/js/116.1ee84ed6.js"><link rel="prefetch" href="/assets/js/117.4952cce2.js"><link rel="prefetch" href="/assets/js/118.306eabfa.js"><link rel="prefetch" href="/assets/js/119.5a4712e9.js"><link rel="prefetch" href="/assets/js/12.c41ab7bc.js"><link rel="prefetch" href="/assets/js/120.496c9660.js"><link rel="prefetch" href="/assets/js/121.e4a22135.js"><link rel="prefetch" href="/assets/js/122.02f82a94.js"><link rel="prefetch" href="/assets/js/123.53c5a24e.js"><link rel="prefetch" href="/assets/js/124.11d8be3e.js"><link rel="prefetch" href="/assets/js/125.c0740874.js"><link rel="prefetch" href="/assets/js/126.9cb2911c.js"><link rel="prefetch" href="/assets/js/127.6f87a638.js"><link rel="prefetch" href="/assets/js/128.456206df.js"><link rel="prefetch" href="/assets/js/129.ce51dc7d.js"><link rel="prefetch" href="/assets/js/13.1147a447.js"><link rel="prefetch" href="/assets/js/130.66718f4c.js"><link rel="prefetch" href="/assets/js/131.713226b7.js"><link rel="prefetch" href="/assets/js/132.6e2b68e3.js"><link rel="prefetch" href="/assets/js/133.11148e38.js"><link rel="prefetch" href="/assets/js/134.8de25763.js"><link rel="prefetch" href="/assets/js/135.961f6693.js"><link rel="prefetch" href="/assets/js/136.8abc4532.js"><link rel="prefetch" href="/assets/js/137.331bfb6b.js"><link rel="prefetch" href="/assets/js/138.f76ee7b9.js"><link rel="prefetch" href="/assets/js/139.578aa70e.js"><link rel="prefetch" href="/assets/js/14.1c437f54.js"><link rel="prefetch" href="/assets/js/140.9f1f28a0.js"><link rel="prefetch" href="/assets/js/141.b08ac1ec.js"><link rel="prefetch" href="/assets/js/142.e5c934cf.js"><link rel="prefetch" href="/assets/js/143.2a9d47c6.js"><link rel="prefetch" href="/assets/js/144.76090f65.js"><link rel="prefetch" href="/assets/js/145.41a54d41.js"><link rel="prefetch" href="/assets/js/146.979b34c1.js"><link rel="prefetch" href="/assets/js/147.46e366af.js"><link rel="prefetch" href="/assets/js/148.efcd2b17.js"><link rel="prefetch" href="/assets/js/149.04135c0b.js"><link rel="prefetch" href="/assets/js/15.cbd21f6a.js"><link rel="prefetch" href="/assets/js/150.679d76bf.js"><link rel="prefetch" href="/assets/js/151.2b0748da.js"><link rel="prefetch" href="/assets/js/152.cee5bbcd.js"><link rel="prefetch" href="/assets/js/153.680b4156.js"><link rel="prefetch" href="/assets/js/154.0c6972fe.js"><link rel="prefetch" href="/assets/js/155.35a3e5ab.js"><link rel="prefetch" href="/assets/js/156.6782d874.js"><link rel="prefetch" href="/assets/js/157.b9fe2583.js"><link rel="prefetch" href="/assets/js/158.96656194.js"><link rel="prefetch" href="/assets/js/159.2a0f7744.js"><link rel="prefetch" href="/assets/js/16.0cc4679e.js"><link rel="prefetch" href="/assets/js/160.c26bf909.js"><link rel="prefetch" href="/assets/js/161.45a3950a.js"><link rel="prefetch" href="/assets/js/162.4a08c069.js"><link rel="prefetch" href="/assets/js/163.a540d00c.js"><link rel="prefetch" href="/assets/js/164.117eb7b8.js"><link rel="prefetch" href="/assets/js/165.4fabe2ea.js"><link rel="prefetch" href="/assets/js/166.27d3bfe9.js"><link rel="prefetch" href="/assets/js/167.c8a74627.js"><link rel="prefetch" href="/assets/js/168.e16111b9.js"><link rel="prefetch" href="/assets/js/169.458ea1d8.js"><link rel="prefetch" href="/assets/js/17.d3f5977b.js"><link rel="prefetch" href="/assets/js/170.4b38adcf.js"><link rel="prefetch" href="/assets/js/171.98cb45b7.js"><link rel="prefetch" href="/assets/js/172.9ca2eb1a.js"><link rel="prefetch" href="/assets/js/173.14074c7f.js"><link rel="prefetch" href="/assets/js/174.8e1f9887.js"><link rel="prefetch" href="/assets/js/175.5989a4ca.js"><link rel="prefetch" href="/assets/js/176.89b35f24.js"><link rel="prefetch" href="/assets/js/177.8ca04666.js"><link rel="prefetch" href="/assets/js/178.f1f78ad5.js"><link rel="prefetch" href="/assets/js/179.a1faadfe.js"><link rel="prefetch" href="/assets/js/18.1a2bbade.js"><link rel="prefetch" href="/assets/js/180.33be0a0d.js"><link rel="prefetch" href="/assets/js/181.074198fc.js"><link rel="prefetch" href="/assets/js/182.2ea92f58.js"><link rel="prefetch" href="/assets/js/183.316f0529.js"><link rel="prefetch" href="/assets/js/184.f6dd5f36.js"><link rel="prefetch" href="/assets/js/185.134f1457.js"><link rel="prefetch" href="/assets/js/186.2aa74077.js"><link rel="prefetch" href="/assets/js/187.3a956aba.js"><link rel="prefetch" href="/assets/js/188.01a6573f.js"><link rel="prefetch" href="/assets/js/189.a8d65b4d.js"><link rel="prefetch" href="/assets/js/19.e062ea88.js"><link rel="prefetch" href="/assets/js/190.c753d8e3.js"><link rel="prefetch" href="/assets/js/191.280fe1e2.js"><link rel="prefetch" href="/assets/js/192.bbc94e32.js"><link rel="prefetch" href="/assets/js/193.41421d14.js"><link rel="prefetch" href="/assets/js/194.15f508e4.js"><link rel="prefetch" href="/assets/js/195.a17f3877.js"><link rel="prefetch" href="/assets/js/196.d17bfcdf.js"><link rel="prefetch" href="/assets/js/197.65791a5a.js"><link rel="prefetch" href="/assets/js/198.0441041e.js"><link rel="prefetch" href="/assets/js/199.538f2285.js"><link rel="prefetch" href="/assets/js/20.6c49f026.js"><link rel="prefetch" href="/assets/js/200.4ff8dbc4.js"><link rel="prefetch" href="/assets/js/201.088ccf86.js"><link rel="prefetch" href="/assets/js/202.8bdad311.js"><link rel="prefetch" href="/assets/js/203.45d3ecc5.js"><link rel="prefetch" href="/assets/js/204.c403aa39.js"><link rel="prefetch" href="/assets/js/205.e992b689.js"><link rel="prefetch" href="/assets/js/206.eed8bd42.js"><link rel="prefetch" href="/assets/js/207.3db1fc87.js"><link rel="prefetch" href="/assets/js/208.27399a7b.js"><link rel="prefetch" href="/assets/js/209.829f007c.js"><link rel="prefetch" href="/assets/js/21.0ed0e55b.js"><link rel="prefetch" href="/assets/js/210.35079683.js"><link rel="prefetch" href="/assets/js/211.94056191.js"><link rel="prefetch" href="/assets/js/212.431059ab.js"><link rel="prefetch" href="/assets/js/213.4d25e21f.js"><link rel="prefetch" href="/assets/js/214.e62f8fc5.js"><link rel="prefetch" href="/assets/js/215.433d7113.js"><link rel="prefetch" href="/assets/js/216.6de56c4d.js"><link rel="prefetch" href="/assets/js/217.ad3e1cd0.js"><link rel="prefetch" href="/assets/js/218.c225521d.js"><link rel="prefetch" href="/assets/js/219.f4241738.js"><link rel="prefetch" href="/assets/js/22.3563c6e0.js"><link rel="prefetch" href="/assets/js/220.ac9c6899.js"><link rel="prefetch" href="/assets/js/221.ff4ee0d2.js"><link rel="prefetch" href="/assets/js/222.20629300.js"><link rel="prefetch" href="/assets/js/223.a5fa0166.js"><link rel="prefetch" href="/assets/js/224.65290c4f.js"><link rel="prefetch" href="/assets/js/225.e698f717.js"><link rel="prefetch" href="/assets/js/226.4b28f10d.js"><link rel="prefetch" href="/assets/js/227.f44065ae.js"><link rel="prefetch" href="/assets/js/228.0b254d68.js"><link rel="prefetch" href="/assets/js/229.560ccb5c.js"><link rel="prefetch" href="/assets/js/23.2bc6a9e3.js"><link rel="prefetch" href="/assets/js/230.2e09449c.js"><link rel="prefetch" href="/assets/js/231.b09e3f00.js"><link rel="prefetch" href="/assets/js/232.eaa54385.js"><link rel="prefetch" href="/assets/js/233.36843a48.js"><link rel="prefetch" href="/assets/js/234.1e3e41c7.js"><link rel="prefetch" href="/assets/js/235.2dff4846.js"><link rel="prefetch" href="/assets/js/236.bb6fd980.js"><link rel="prefetch" href="/assets/js/237.e97364da.js"><link rel="prefetch" href="/assets/js/238.d8ce22f3.js"><link rel="prefetch" href="/assets/js/239.be791e5e.js"><link rel="prefetch" href="/assets/js/24.4b60795e.js"><link rel="prefetch" href="/assets/js/240.3927116f.js"><link rel="prefetch" href="/assets/js/241.6539a7f9.js"><link rel="prefetch" href="/assets/js/242.1241e424.js"><link rel="prefetch" href="/assets/js/243.a07d3be3.js"><link rel="prefetch" href="/assets/js/244.f98f98a1.js"><link rel="prefetch" href="/assets/js/245.ecb7c922.js"><link rel="prefetch" href="/assets/js/246.95ed23ce.js"><link rel="prefetch" href="/assets/js/247.fb5d42c6.js"><link rel="prefetch" href="/assets/js/248.f7b4f364.js"><link rel="prefetch" href="/assets/js/249.ac22d922.js"><link rel="prefetch" href="/assets/js/25.ef18cc01.js"><link rel="prefetch" href="/assets/js/250.01fbf76b.js"><link rel="prefetch" href="/assets/js/251.08f19bbd.js"><link rel="prefetch" href="/assets/js/252.9f11061d.js"><link rel="prefetch" href="/assets/js/253.cd7f85b9.js"><link rel="prefetch" href="/assets/js/254.2493e550.js"><link rel="prefetch" href="/assets/js/255.ac6d41ee.js"><link rel="prefetch" href="/assets/js/256.068eb5a6.js"><link rel="prefetch" href="/assets/js/257.b108c715.js"><link rel="prefetch" href="/assets/js/258.d614b5d4.js"><link rel="prefetch" href="/assets/js/259.87ba5ef3.js"><link rel="prefetch" href="/assets/js/26.5baa4d2c.js"><link rel="prefetch" href="/assets/js/260.c771e39d.js"><link rel="prefetch" href="/assets/js/261.0dbaf460.js"><link rel="prefetch" href="/assets/js/262.35e64a26.js"><link rel="prefetch" href="/assets/js/263.c16fca32.js"><link rel="prefetch" href="/assets/js/264.ea414912.js"><link rel="prefetch" href="/assets/js/265.f2e0d5bb.js"><link rel="prefetch" href="/assets/js/266.629a2d15.js"><link rel="prefetch" href="/assets/js/267.c7332e80.js"><link rel="prefetch" href="/assets/js/268.8be99f76.js"><link rel="prefetch" href="/assets/js/269.452ff2d4.js"><link rel="prefetch" href="/assets/js/27.2a2950d8.js"><link rel="prefetch" href="/assets/js/270.a5c429cb.js"><link rel="prefetch" href="/assets/js/271.1ad3cd83.js"><link rel="prefetch" href="/assets/js/272.354cef59.js"><link rel="prefetch" href="/assets/js/273.681156b7.js"><link rel="prefetch" href="/assets/js/274.6c51e7ae.js"><link rel="prefetch" href="/assets/js/275.24ef01b4.js"><link rel="prefetch" href="/assets/js/276.afeb2acd.js"><link rel="prefetch" href="/assets/js/277.6472c22d.js"><link rel="prefetch" href="/assets/js/278.416d9788.js"><link rel="prefetch" href="/assets/js/279.c190fbc9.js"><link rel="prefetch" href="/assets/js/28.6320d8c1.js"><link rel="prefetch" href="/assets/js/280.28b1b955.js"><link rel="prefetch" href="/assets/js/281.77afd7c5.js"><link rel="prefetch" href="/assets/js/282.eee0e9c0.js"><link rel="prefetch" href="/assets/js/283.e59fb0e5.js"><link rel="prefetch" href="/assets/js/284.9c6ff275.js"><link rel="prefetch" href="/assets/js/285.3e2d030a.js"><link rel="prefetch" href="/assets/js/286.d7562f9b.js"><link rel="prefetch" href="/assets/js/287.9e228e80.js"><link rel="prefetch" href="/assets/js/288.f9448d7d.js"><link rel="prefetch" href="/assets/js/289.30726f95.js"><link rel="prefetch" href="/assets/js/29.a420635f.js"><link rel="prefetch" href="/assets/js/290.f79765e2.js"><link rel="prefetch" href="/assets/js/291.0943618c.js"><link rel="prefetch" href="/assets/js/292.bd04f6db.js"><link rel="prefetch" href="/assets/js/293.776f4c0d.js"><link rel="prefetch" href="/assets/js/294.54e52863.js"><link rel="prefetch" href="/assets/js/295.bd033d69.js"><link rel="prefetch" href="/assets/js/296.1090c539.js"><link rel="prefetch" href="/assets/js/297.ec37f6e8.js"><link rel="prefetch" href="/assets/js/298.fa434214.js"><link rel="prefetch" href="/assets/js/299.50bd7c87.js"><link rel="prefetch" href="/assets/js/30.6c81ca7b.js"><link rel="prefetch" href="/assets/js/300.7a2c6632.js"><link rel="prefetch" href="/assets/js/301.4ae4e645.js"><link rel="prefetch" href="/assets/js/302.e1ef7459.js"><link rel="prefetch" href="/assets/js/303.3894068b.js"><link rel="prefetch" href="/assets/js/304.840b09e3.js"><link rel="prefetch" href="/assets/js/305.40ec0bf6.js"><link rel="prefetch" href="/assets/js/306.9fa4d8aa.js"><link rel="prefetch" href="/assets/js/307.33656e76.js"><link rel="prefetch" href="/assets/js/308.19398f71.js"><link rel="prefetch" href="/assets/js/309.bde6f12f.js"><link rel="prefetch" href="/assets/js/31.2b4f2752.js"><link rel="prefetch" href="/assets/js/310.69ced632.js"><link rel="prefetch" href="/assets/js/311.c8e57d0e.js"><link rel="prefetch" href="/assets/js/312.80c4d6a7.js"><link rel="prefetch" href="/assets/js/313.14060a06.js"><link rel="prefetch" href="/assets/js/314.29165d83.js"><link rel="prefetch" href="/assets/js/315.901aabf1.js"><link rel="prefetch" href="/assets/js/316.7f0d18e3.js"><link rel="prefetch" href="/assets/js/317.112de6ec.js"><link rel="prefetch" href="/assets/js/318.091ea533.js"><link rel="prefetch" href="/assets/js/319.25ca175e.js"><link rel="prefetch" href="/assets/js/32.ab03e16f.js"><link rel="prefetch" href="/assets/js/320.b89e85c9.js"><link rel="prefetch" href="/assets/js/321.69316136.js"><link rel="prefetch" href="/assets/js/322.567512f0.js"><link rel="prefetch" href="/assets/js/323.2d67bb75.js"><link rel="prefetch" href="/assets/js/324.c41411db.js"><link rel="prefetch" href="/assets/js/325.a412ca77.js"><link rel="prefetch" href="/assets/js/326.22408ce6.js"><link rel="prefetch" href="/assets/js/327.33524443.js"><link rel="prefetch" href="/assets/js/328.561ebeb1.js"><link rel="prefetch" href="/assets/js/329.d7a280e4.js"><link rel="prefetch" href="/assets/js/33.199f45ed.js"><link rel="prefetch" href="/assets/js/330.d01a7e1b.js"><link rel="prefetch" href="/assets/js/331.a3ad2556.js"><link rel="prefetch" href="/assets/js/332.36ad912a.js"><link rel="prefetch" href="/assets/js/333.2fb229c4.js"><link rel="prefetch" href="/assets/js/334.d170f507.js"><link rel="prefetch" href="/assets/js/335.90ca0539.js"><link rel="prefetch" href="/assets/js/336.454d4374.js"><link rel="prefetch" href="/assets/js/337.dba45eb4.js"><link rel="prefetch" href="/assets/js/338.c8e4ba66.js"><link rel="prefetch" href="/assets/js/339.ae85118e.js"><link rel="prefetch" href="/assets/js/34.d0c7a02e.js"><link rel="prefetch" href="/assets/js/340.7033b85b.js"><link rel="prefetch" href="/assets/js/341.13cfe1aa.js"><link rel="prefetch" href="/assets/js/342.b33302b5.js"><link rel="prefetch" href="/assets/js/343.946f30dc.js"><link rel="prefetch" href="/assets/js/344.b2add405.js"><link rel="prefetch" href="/assets/js/345.12433fa3.js"><link rel="prefetch" href="/assets/js/346.b1bdfeba.js"><link rel="prefetch" href="/assets/js/347.53530bff.js"><link rel="prefetch" href="/assets/js/348.48aa580e.js"><link rel="prefetch" href="/assets/js/349.53c4baca.js"><link rel="prefetch" href="/assets/js/35.5512348f.js"><link rel="prefetch" href="/assets/js/350.e4b2d6e6.js"><link rel="prefetch" href="/assets/js/351.d41b01c1.js"><link rel="prefetch" href="/assets/js/352.1c4d1250.js"><link rel="prefetch" href="/assets/js/353.7fd27c0f.js"><link rel="prefetch" href="/assets/js/354.47199c90.js"><link rel="prefetch" href="/assets/js/355.68bccab4.js"><link rel="prefetch" href="/assets/js/356.e3602eb5.js"><link rel="prefetch" href="/assets/js/357.cd5ce764.js"><link rel="prefetch" href="/assets/js/358.bee621d4.js"><link rel="prefetch" href="/assets/js/359.648aa4f0.js"><link rel="prefetch" href="/assets/js/36.bdebdf29.js"><link rel="prefetch" href="/assets/js/360.439f5fae.js"><link rel="prefetch" href="/assets/js/361.39f782b4.js"><link rel="prefetch" href="/assets/js/362.106acf4c.js"><link rel="prefetch" href="/assets/js/363.562a4e1e.js"><link rel="prefetch" href="/assets/js/364.5940b069.js"><link rel="prefetch" href="/assets/js/365.e429c365.js"><link rel="prefetch" href="/assets/js/366.cc650df8.js"><link rel="prefetch" href="/assets/js/367.347592c9.js"><link rel="prefetch" href="/assets/js/368.d68ce88d.js"><link rel="prefetch" href="/assets/js/369.034e7f1e.js"><link rel="prefetch" href="/assets/js/37.9d026956.js"><link rel="prefetch" href="/assets/js/370.ac6fc7a5.js"><link rel="prefetch" href="/assets/js/371.e70219a6.js"><link rel="prefetch" href="/assets/js/372.c449fc49.js"><link rel="prefetch" href="/assets/js/373.f07bea72.js"><link rel="prefetch" href="/assets/js/374.8152408f.js"><link rel="prefetch" href="/assets/js/375.63c70dab.js"><link rel="prefetch" href="/assets/js/376.06de19db.js"><link rel="prefetch" href="/assets/js/377.2319ddb1.js"><link rel="prefetch" href="/assets/js/378.4821e23c.js"><link rel="prefetch" href="/assets/js/379.54a13769.js"><link rel="prefetch" href="/assets/js/38.23e83578.js"><link rel="prefetch" href="/assets/js/380.dac4cd46.js"><link rel="prefetch" href="/assets/js/381.8f83d1d7.js"><link rel="prefetch" href="/assets/js/382.e76e7d88.js"><link rel="prefetch" href="/assets/js/383.df731ee4.js"><link rel="prefetch" href="/assets/js/384.5093369e.js"><link rel="prefetch" href="/assets/js/385.ee576341.js"><link rel="prefetch" href="/assets/js/386.087a29a9.js"><link rel="prefetch" href="/assets/js/387.9f44d03b.js"><link rel="prefetch" href="/assets/js/388.a3f70992.js"><link rel="prefetch" href="/assets/js/389.df6e2ced.js"><link rel="prefetch" href="/assets/js/39.e9699d7f.js"><link rel="prefetch" href="/assets/js/390.c377efca.js"><link rel="prefetch" href="/assets/js/391.d7747385.js"><link rel="prefetch" href="/assets/js/392.bf8e8c1a.js"><link rel="prefetch" href="/assets/js/393.b4ed3be0.js"><link rel="prefetch" href="/assets/js/394.48eb505a.js"><link rel="prefetch" href="/assets/js/395.d9cd4812.js"><link rel="prefetch" href="/assets/js/396.b386a6b5.js"><link rel="prefetch" href="/assets/js/397.d19960fa.js"><link rel="prefetch" href="/assets/js/398.15f66e2a.js"><link rel="prefetch" href="/assets/js/399.cc4af83b.js"><link rel="prefetch" href="/assets/js/40.3a541653.js"><link rel="prefetch" href="/assets/js/400.d99e4b93.js"><link rel="prefetch" href="/assets/js/401.13fa06dd.js"><link rel="prefetch" href="/assets/js/402.3629b866.js"><link rel="prefetch" href="/assets/js/403.5826b040.js"><link rel="prefetch" href="/assets/js/404.d4b35549.js"><link rel="prefetch" href="/assets/js/405.9142a002.js"><link rel="prefetch" href="/assets/js/406.ba50e04d.js"><link rel="prefetch" href="/assets/js/407.b5271c6f.js"><link rel="prefetch" href="/assets/js/408.18baa241.js"><link rel="prefetch" href="/assets/js/409.6151d46b.js"><link rel="prefetch" href="/assets/js/41.b10ef41f.js"><link rel="prefetch" href="/assets/js/410.bb1fd058.js"><link rel="prefetch" href="/assets/js/411.9273fd47.js"><link rel="prefetch" href="/assets/js/412.d6b790c1.js"><link rel="prefetch" href="/assets/js/413.4c5a30bb.js"><link rel="prefetch" href="/assets/js/414.01aa0e0a.js"><link rel="prefetch" href="/assets/js/415.2633ad61.js"><link rel="prefetch" href="/assets/js/416.7a2263a9.js"><link rel="prefetch" href="/assets/js/417.98368241.js"><link rel="prefetch" href="/assets/js/418.ffeb9c9c.js"><link rel="prefetch" href="/assets/js/419.633f9efe.js"><link rel="prefetch" href="/assets/js/42.aa8b7c99.js"><link rel="prefetch" href="/assets/js/420.69868f4a.js"><link rel="prefetch" href="/assets/js/421.937d87cc.js"><link rel="prefetch" href="/assets/js/422.375fe09b.js"><link rel="prefetch" href="/assets/js/423.8d335fd6.js"><link rel="prefetch" href="/assets/js/424.d5b181d7.js"><link rel="prefetch" href="/assets/js/425.e06749ea.js"><link rel="prefetch" href="/assets/js/426.d7a23361.js"><link rel="prefetch" href="/assets/js/427.c26079c3.js"><link rel="prefetch" href="/assets/js/428.788e60b3.js"><link rel="prefetch" href="/assets/js/429.212c3091.js"><link rel="prefetch" href="/assets/js/43.bbf1f09a.js"><link rel="prefetch" href="/assets/js/430.e156b1fa.js"><link rel="prefetch" href="/assets/js/431.b41e44c6.js"><link rel="prefetch" href="/assets/js/432.7534e280.js"><link rel="prefetch" href="/assets/js/433.3d203e2b.js"><link rel="prefetch" href="/assets/js/434.41bb5350.js"><link rel="prefetch" href="/assets/js/435.a5c93fd3.js"><link rel="prefetch" href="/assets/js/436.60910866.js"><link rel="prefetch" href="/assets/js/437.7ae74f40.js"><link rel="prefetch" href="/assets/js/438.dc802af3.js"><link rel="prefetch" href="/assets/js/439.0de7c2a4.js"><link rel="prefetch" href="/assets/js/44.c0079627.js"><link rel="prefetch" href="/assets/js/440.43bc725f.js"><link rel="prefetch" href="/assets/js/441.1402dd2a.js"><link rel="prefetch" href="/assets/js/442.6106e1be.js"><link rel="prefetch" href="/assets/js/443.40909ac7.js"><link rel="prefetch" href="/assets/js/444.e506898d.js"><link rel="prefetch" href="/assets/js/445.8636f7a3.js"><link rel="prefetch" href="/assets/js/446.de915ed4.js"><link rel="prefetch" href="/assets/js/447.c7ac8e6e.js"><link rel="prefetch" href="/assets/js/448.9797a750.js"><link rel="prefetch" href="/assets/js/449.5d1f4748.js"><link rel="prefetch" href="/assets/js/45.2a09d581.js"><link rel="prefetch" href="/assets/js/450.42babefe.js"><link rel="prefetch" href="/assets/js/451.ee1b8ff8.js"><link rel="prefetch" href="/assets/js/452.7536e7c2.js"><link rel="prefetch" href="/assets/js/453.39a21d52.js"><link rel="prefetch" href="/assets/js/454.6511d1e1.js"><link rel="prefetch" href="/assets/js/455.2abb8ea0.js"><link rel="prefetch" href="/assets/js/456.5724d799.js"><link rel="prefetch" href="/assets/js/457.c32c0755.js"><link rel="prefetch" href="/assets/js/458.f67c539b.js"><link rel="prefetch" href="/assets/js/459.1634e8da.js"><link rel="prefetch" href="/assets/js/46.58b302e4.js"><link rel="prefetch" href="/assets/js/460.a22ac002.js"><link rel="prefetch" href="/assets/js/461.2c152148.js"><link rel="prefetch" href="/assets/js/462.14b038cf.js"><link rel="prefetch" href="/assets/js/463.dd0a3a00.js"><link rel="prefetch" href="/assets/js/464.f22ba288.js"><link rel="prefetch" href="/assets/js/465.9c187041.js"><link rel="prefetch" href="/assets/js/466.9957dd67.js"><link rel="prefetch" href="/assets/js/467.047041e8.js"><link rel="prefetch" href="/assets/js/468.425b6f20.js"><link rel="prefetch" href="/assets/js/469.2f70ecf7.js"><link rel="prefetch" href="/assets/js/47.987d79be.js"><link rel="prefetch" href="/assets/js/470.602b7d98.js"><link rel="prefetch" href="/assets/js/471.ddabe1b6.js"><link rel="prefetch" href="/assets/js/472.3a1ad521.js"><link rel="prefetch" href="/assets/js/473.2be352ab.js"><link rel="prefetch" href="/assets/js/474.e9c805de.js"><link rel="prefetch" href="/assets/js/475.93cab6cb.js"><link rel="prefetch" href="/assets/js/476.89384fa4.js"><link rel="prefetch" href="/assets/js/477.2b282ee8.js"><link rel="prefetch" href="/assets/js/478.27790491.js"><link rel="prefetch" href="/assets/js/479.2b728ba6.js"><link rel="prefetch" href="/assets/js/48.0e76d761.js"><link rel="prefetch" href="/assets/js/480.bd0beea9.js"><link rel="prefetch" href="/assets/js/481.004a0005.js"><link rel="prefetch" href="/assets/js/482.d9c6dc45.js"><link rel="prefetch" href="/assets/js/483.e7842361.js"><link rel="prefetch" href="/assets/js/484.702ac9a3.js"><link rel="prefetch" href="/assets/js/485.d38ba4c2.js"><link rel="prefetch" href="/assets/js/486.8a0cd211.js"><link rel="prefetch" href="/assets/js/487.18e243bb.js"><link rel="prefetch" href="/assets/js/488.cb0ad1bf.js"><link rel="prefetch" href="/assets/js/489.7c7adc5c.js"><link rel="prefetch" href="/assets/js/49.83e0619b.js"><link rel="prefetch" href="/assets/js/490.3f86a6a4.js"><link rel="prefetch" href="/assets/js/491.c1c90b4f.js"><link rel="prefetch" href="/assets/js/492.5658313d.js"><link rel="prefetch" href="/assets/js/493.9b953b18.js"><link rel="prefetch" href="/assets/js/494.80e3d4f4.js"><link rel="prefetch" href="/assets/js/495.66650a67.js"><link rel="prefetch" href="/assets/js/496.4e0d753b.js"><link rel="prefetch" href="/assets/js/497.1837b7c2.js"><link rel="prefetch" href="/assets/js/498.e2dcd450.js"><link rel="prefetch" href="/assets/js/499.4d5022f2.js"><link rel="prefetch" href="/assets/js/5.f343fd5d.js"><link rel="prefetch" href="/assets/js/50.6716fe91.js"><link rel="prefetch" href="/assets/js/500.10c0ee69.js"><link rel="prefetch" href="/assets/js/501.be3f9599.js"><link rel="prefetch" href="/assets/js/502.27844894.js"><link rel="prefetch" href="/assets/js/503.15f84a9b.js"><link rel="prefetch" href="/assets/js/504.60780a8e.js"><link rel="prefetch" href="/assets/js/505.6f9bed41.js"><link rel="prefetch" href="/assets/js/506.3e19b413.js"><link rel="prefetch" href="/assets/js/507.a12a02cb.js"><link rel="prefetch" href="/assets/js/508.b1384524.js"><link rel="prefetch" href="/assets/js/509.c74ef6c0.js"><link rel="prefetch" href="/assets/js/51.bc8d5aaf.js"><link rel="prefetch" href="/assets/js/510.266a6048.js"><link rel="prefetch" href="/assets/js/511.be98a2ef.js"><link rel="prefetch" href="/assets/js/512.e033e89e.js"><link rel="prefetch" href="/assets/js/513.837b9052.js"><link rel="prefetch" href="/assets/js/514.38271d19.js"><link rel="prefetch" href="/assets/js/515.c08327b5.js"><link rel="prefetch" href="/assets/js/516.3d573fdf.js"><link rel="prefetch" href="/assets/js/517.5406a8bd.js"><link rel="prefetch" href="/assets/js/518.543bea6f.js"><link rel="prefetch" href="/assets/js/519.e4967ce6.js"><link rel="prefetch" href="/assets/js/52.20603f07.js"><link rel="prefetch" href="/assets/js/520.0a863135.js"><link rel="prefetch" href="/assets/js/521.80c26149.js"><link rel="prefetch" href="/assets/js/522.5d0549ee.js"><link rel="prefetch" href="/assets/js/523.4b5d705c.js"><link rel="prefetch" href="/assets/js/524.24354cd8.js"><link rel="prefetch" href="/assets/js/525.d201b688.js"><link rel="prefetch" href="/assets/js/526.f405c35a.js"><link rel="prefetch" href="/assets/js/527.921d252f.js"><link rel="prefetch" href="/assets/js/528.cb45a5dd.js"><link rel="prefetch" href="/assets/js/529.aeec69e2.js"><link rel="prefetch" href="/assets/js/53.9604c447.js"><link rel="prefetch" href="/assets/js/530.7d5514c0.js"><link rel="prefetch" href="/assets/js/531.de381ab2.js"><link rel="prefetch" href="/assets/js/532.31b6e993.js"><link rel="prefetch" href="/assets/js/533.23335bff.js"><link rel="prefetch" href="/assets/js/534.131d260d.js"><link rel="prefetch" href="/assets/js/535.3057e7f2.js"><link rel="prefetch" href="/assets/js/536.1df4cc6e.js"><link rel="prefetch" href="/assets/js/537.c23a3391.js"><link rel="prefetch" href="/assets/js/538.ac3546d3.js"><link rel="prefetch" href="/assets/js/539.36137525.js"><link rel="prefetch" href="/assets/js/54.841e8e8f.js"><link rel="prefetch" href="/assets/js/540.f9171241.js"><link rel="prefetch" href="/assets/js/541.00a9732f.js"><link rel="prefetch" href="/assets/js/542.d981dcf7.js"><link rel="prefetch" href="/assets/js/543.0016cdef.js"><link rel="prefetch" href="/assets/js/544.b24fa17d.js"><link rel="prefetch" href="/assets/js/545.8adcd15c.js"><link rel="prefetch" href="/assets/js/546.189f10ef.js"><link rel="prefetch" href="/assets/js/547.d47175ac.js"><link rel="prefetch" href="/assets/js/548.67ed7a21.js"><link rel="prefetch" href="/assets/js/549.a72c957e.js"><link rel="prefetch" href="/assets/js/55.eccc64f8.js"><link rel="prefetch" href="/assets/js/550.c127415f.js"><link rel="prefetch" href="/assets/js/551.288648b2.js"><link rel="prefetch" href="/assets/js/552.5191109c.js"><link rel="prefetch" href="/assets/js/553.a0417c79.js"><link rel="prefetch" href="/assets/js/554.05224c83.js"><link rel="prefetch" href="/assets/js/555.d95f24bd.js"><link rel="prefetch" href="/assets/js/556.42a17364.js"><link rel="prefetch" href="/assets/js/557.a066d457.js"><link rel="prefetch" href="/assets/js/558.1f4641c3.js"><link rel="prefetch" href="/assets/js/559.f85fd85a.js"><link rel="prefetch" href="/assets/js/56.9ede6cf7.js"><link rel="prefetch" href="/assets/js/560.c486ead6.js"><link rel="prefetch" href="/assets/js/561.5654ef71.js"><link rel="prefetch" href="/assets/js/562.8ac06965.js"><link rel="prefetch" href="/assets/js/563.209407dd.js"><link rel="prefetch" href="/assets/js/564.4da5848b.js"><link rel="prefetch" href="/assets/js/565.0ea0c2cb.js"><link rel="prefetch" href="/assets/js/566.fbb62b05.js"><link rel="prefetch" href="/assets/js/567.0454bee2.js"><link rel="prefetch" href="/assets/js/568.5aad57f8.js"><link rel="prefetch" href="/assets/js/569.b4b199ad.js"><link rel="prefetch" href="/assets/js/57.2e9b38e9.js"><link rel="prefetch" href="/assets/js/570.890f1d05.js"><link rel="prefetch" href="/assets/js/571.56e5f721.js"><link rel="prefetch" href="/assets/js/572.fa3418f1.js"><link rel="prefetch" href="/assets/js/573.224ada77.js"><link rel="prefetch" href="/assets/js/574.4cc85330.js"><link rel="prefetch" href="/assets/js/575.61a17f5e.js"><link rel="prefetch" href="/assets/js/576.0ec5efb8.js"><link rel="prefetch" href="/assets/js/577.6bc915dd.js"><link rel="prefetch" href="/assets/js/578.fd4e39e7.js"><link rel="prefetch" href="/assets/js/579.0238c950.js"><link rel="prefetch" href="/assets/js/58.f28ad3cc.js"><link rel="prefetch" href="/assets/js/580.a08c6c02.js"><link rel="prefetch" href="/assets/js/581.392f9c6f.js"><link rel="prefetch" href="/assets/js/582.2f59e9f2.js"><link rel="prefetch" href="/assets/js/583.2097fe85.js"><link rel="prefetch" href="/assets/js/584.f0d8c622.js"><link rel="prefetch" href="/assets/js/585.85fab1f2.js"><link rel="prefetch" href="/assets/js/586.c359098c.js"><link rel="prefetch" href="/assets/js/587.1dff90c3.js"><link rel="prefetch" href="/assets/js/588.6afc16eb.js"><link rel="prefetch" href="/assets/js/589.4337cfee.js"><link rel="prefetch" href="/assets/js/59.9079a4f5.js"><link rel="prefetch" href="/assets/js/590.f969cc18.js"><link rel="prefetch" href="/assets/js/591.dfceaca2.js"><link rel="prefetch" href="/assets/js/592.b670f7b8.js"><link rel="prefetch" href="/assets/js/593.85ff3e7e.js"><link rel="prefetch" href="/assets/js/594.87d3c73b.js"><link rel="prefetch" href="/assets/js/595.18f2a1df.js"><link rel="prefetch" href="/assets/js/596.adb07b39.js"><link rel="prefetch" href="/assets/js/597.4bfdae44.js"><link rel="prefetch" href="/assets/js/598.a4f73bf5.js"><link rel="prefetch" href="/assets/js/599.5b85b7f2.js"><link rel="prefetch" href="/assets/js/6.6f5ae702.js"><link rel="prefetch" href="/assets/js/60.3095e21a.js"><link rel="prefetch" href="/assets/js/600.98cef029.js"><link rel="prefetch" href="/assets/js/601.34cfecd2.js"><link rel="prefetch" href="/assets/js/602.afaf2e1f.js"><link rel="prefetch" href="/assets/js/603.5f081041.js"><link rel="prefetch" href="/assets/js/604.a55dc3e4.js"><link rel="prefetch" href="/assets/js/605.cc600bca.js"><link rel="prefetch" href="/assets/js/606.9e0874e1.js"><link rel="prefetch" href="/assets/js/607.bd0a2835.js"><link rel="prefetch" href="/assets/js/608.e3c0bb6d.js"><link rel="prefetch" href="/assets/js/609.968adfbe.js"><link rel="prefetch" href="/assets/js/61.cd58c0e2.js"><link rel="prefetch" href="/assets/js/610.6ddb82e2.js"><link rel="prefetch" href="/assets/js/611.f6573e33.js"><link rel="prefetch" href="/assets/js/612.cd703232.js"><link rel="prefetch" href="/assets/js/613.5ae48097.js"><link rel="prefetch" href="/assets/js/614.c9fc5628.js"><link rel="prefetch" href="/assets/js/615.5f3c1162.js"><link rel="prefetch" href="/assets/js/616.3efeed17.js"><link rel="prefetch" href="/assets/js/617.25dec672.js"><link rel="prefetch" href="/assets/js/618.b53f21b6.js"><link rel="prefetch" href="/assets/js/619.e0c2de74.js"><link rel="prefetch" href="/assets/js/62.aa4d202d.js"><link rel="prefetch" href="/assets/js/620.88136c6a.js"><link rel="prefetch" href="/assets/js/621.494122df.js"><link rel="prefetch" href="/assets/js/622.e2a6e4bd.js"><link rel="prefetch" href="/assets/js/623.20a56d61.js"><link rel="prefetch" href="/assets/js/624.602dd933.js"><link rel="prefetch" href="/assets/js/625.70f44f60.js"><link rel="prefetch" href="/assets/js/626.11524978.js"><link rel="prefetch" href="/assets/js/627.b3badb72.js"><link rel="prefetch" href="/assets/js/628.e613665e.js"><link rel="prefetch" href="/assets/js/629.20e73b43.js"><link rel="prefetch" href="/assets/js/63.f7cd40f4.js"><link rel="prefetch" href="/assets/js/630.6099312f.js"><link rel="prefetch" href="/assets/js/631.669bcda0.js"><link rel="prefetch" href="/assets/js/632.d33f5ec9.js"><link rel="prefetch" href="/assets/js/633.211456ee.js"><link rel="prefetch" href="/assets/js/634.ea9d07ae.js"><link rel="prefetch" href="/assets/js/635.f22368f1.js"><link rel="prefetch" href="/assets/js/636.ebe249f7.js"><link rel="prefetch" href="/assets/js/637.7b645ab3.js"><link rel="prefetch" href="/assets/js/638.4565c395.js"><link rel="prefetch" href="/assets/js/639.c5144f9c.js"><link rel="prefetch" href="/assets/js/64.8cd3aa43.js"><link rel="prefetch" href="/assets/js/640.2dc2eba9.js"><link rel="prefetch" href="/assets/js/641.70155ce7.js"><link rel="prefetch" href="/assets/js/642.c55f5ca8.js"><link rel="prefetch" href="/assets/js/643.69a5b8e5.js"><link rel="prefetch" href="/assets/js/644.84431935.js"><link rel="prefetch" href="/assets/js/645.5119ebc2.js"><link rel="prefetch" href="/assets/js/646.506fc745.js"><link rel="prefetch" href="/assets/js/647.e5f03652.js"><link rel="prefetch" href="/assets/js/648.47ae0cc5.js"><link rel="prefetch" href="/assets/js/649.b3a67529.js"><link rel="prefetch" href="/assets/js/65.14b3da5d.js"><link rel="prefetch" href="/assets/js/650.89765bb0.js"><link rel="prefetch" href="/assets/js/651.19b73cf8.js"><link rel="prefetch" href="/assets/js/652.4436725f.js"><link rel="prefetch" href="/assets/js/653.391168ff.js"><link rel="prefetch" href="/assets/js/654.8b449d07.js"><link rel="prefetch" href="/assets/js/655.27051c8c.js"><link rel="prefetch" href="/assets/js/656.7adaae31.js"><link rel="prefetch" href="/assets/js/657.4fee46d2.js"><link rel="prefetch" href="/assets/js/658.0243a6e8.js"><link rel="prefetch" href="/assets/js/659.f69398bc.js"><link rel="prefetch" href="/assets/js/66.899fc260.js"><link rel="prefetch" href="/assets/js/660.5e51ab7c.js"><link rel="prefetch" href="/assets/js/661.980d3d5a.js"><link rel="prefetch" href="/assets/js/662.79643730.js"><link rel="prefetch" href="/assets/js/663.d030bd1d.js"><link rel="prefetch" href="/assets/js/664.32b3c0e8.js"><link rel="prefetch" href="/assets/js/665.384c456b.js"><link rel="prefetch" href="/assets/js/666.2672eb36.js"><link rel="prefetch" href="/assets/js/667.2ca85ff9.js"><link rel="prefetch" href="/assets/js/668.b80ef3b4.js"><link rel="prefetch" href="/assets/js/669.41f08cb1.js"><link rel="prefetch" href="/assets/js/67.c0e799e4.js"><link rel="prefetch" href="/assets/js/670.48512f45.js"><link rel="prefetch" href="/assets/js/671.93e1cdd9.js"><link rel="prefetch" href="/assets/js/672.aa2a7e31.js"><link rel="prefetch" href="/assets/js/673.b19ed80d.js"><link rel="prefetch" href="/assets/js/674.0337bf32.js"><link rel="prefetch" href="/assets/js/675.88a9d569.js"><link rel="prefetch" href="/assets/js/676.7fd2de1c.js"><link rel="prefetch" href="/assets/js/677.1356b477.js"><link rel="prefetch" href="/assets/js/678.d99fd658.js"><link rel="prefetch" href="/assets/js/679.a2e40bc7.js"><link rel="prefetch" href="/assets/js/68.2e72dacb.js"><link rel="prefetch" href="/assets/js/680.58e5d76e.js"><link rel="prefetch" href="/assets/js/681.2e66d773.js"><link rel="prefetch" href="/assets/js/682.42526013.js"><link rel="prefetch" href="/assets/js/683.447d4972.js"><link rel="prefetch" href="/assets/js/684.19beb22a.js"><link rel="prefetch" href="/assets/js/685.cd3fd615.js"><link rel="prefetch" href="/assets/js/686.c6200f3f.js"><link rel="prefetch" href="/assets/js/687.3d6cf8bb.js"><link rel="prefetch" href="/assets/js/688.e9ddd041.js"><link rel="prefetch" href="/assets/js/689.74bb6414.js"><link rel="prefetch" href="/assets/js/69.d29a7787.js"><link rel="prefetch" href="/assets/js/690.82b51acd.js"><link rel="prefetch" href="/assets/js/691.a6edc5c3.js"><link rel="prefetch" href="/assets/js/692.c5fd2fa7.js"><link rel="prefetch" href="/assets/js/693.0c0b8126.js"><link rel="prefetch" href="/assets/js/694.551ae4d1.js"><link rel="prefetch" href="/assets/js/695.2801a2f2.js"><link rel="prefetch" href="/assets/js/696.8723006b.js"><link rel="prefetch" href="/assets/js/697.275e71c7.js"><link rel="prefetch" href="/assets/js/698.431e2bfb.js"><link rel="prefetch" href="/assets/js/699.c82907d3.js"><link rel="prefetch" href="/assets/js/7.c8b0ee6b.js"><link rel="prefetch" href="/assets/js/70.53b18677.js"><link rel="prefetch" href="/assets/js/700.9faf8917.js"><link rel="prefetch" href="/assets/js/701.5ce77f04.js"><link rel="prefetch" href="/assets/js/702.488262eb.js"><link rel="prefetch" href="/assets/js/703.8f79363d.js"><link rel="prefetch" href="/assets/js/704.a4cfe8cb.js"><link rel="prefetch" href="/assets/js/705.4f1759eb.js"><link rel="prefetch" href="/assets/js/706.baf03b10.js"><link rel="prefetch" href="/assets/js/707.48c01840.js"><link rel="prefetch" href="/assets/js/708.b3cda177.js"><link rel="prefetch" href="/assets/js/709.260cc3a8.js"><link rel="prefetch" href="/assets/js/71.b44506bc.js"><link rel="prefetch" href="/assets/js/710.e4fa6646.js"><link rel="prefetch" href="/assets/js/711.7816aba5.js"><link rel="prefetch" href="/assets/js/712.14939ffd.js"><link rel="prefetch" href="/assets/js/72.9793c1ce.js"><link rel="prefetch" href="/assets/js/73.b4d37c7e.js"><link rel="prefetch" href="/assets/js/74.b816cbc7.js"><link rel="prefetch" href="/assets/js/75.9f45a274.js"><link rel="prefetch" href="/assets/js/76.4921e235.js"><link rel="prefetch" href="/assets/js/77.f9258c97.js"><link rel="prefetch" href="/assets/js/78.55656c0f.js"><link rel="prefetch" href="/assets/js/79.b5784c72.js"><link rel="prefetch" href="/assets/js/8.44118d7c.js"><link rel="prefetch" href="/assets/js/80.98240933.js"><link rel="prefetch" href="/assets/js/81.5421fa90.js"><link rel="prefetch" href="/assets/js/82.72a10ccf.js"><link rel="prefetch" href="/assets/js/83.abdca93e.js"><link rel="prefetch" href="/assets/js/84.5d0190e3.js"><link rel="prefetch" href="/assets/js/85.5d2a1647.js"><link rel="prefetch" href="/assets/js/86.5aea5730.js"><link rel="prefetch" href="/assets/js/87.bfe2bb57.js"><link rel="prefetch" href="/assets/js/88.4097611c.js"><link rel="prefetch" href="/assets/js/89.e5a98da0.js"><link rel="prefetch" href="/assets/js/9.612b54fd.js"><link rel="prefetch" href="/assets/js/90.5564a69b.js"><link rel="prefetch" href="/assets/js/91.ff219511.js"><link rel="prefetch" href="/assets/js/92.8191f073.js"><link rel="prefetch" href="/assets/js/93.4b6ecb16.js"><link rel="prefetch" href="/assets/js/94.fd999a73.js"><link rel="prefetch" href="/assets/js/95.c96c310d.js"><link rel="prefetch" href="/assets/js/96.2eb0ab2f.js"><link rel="prefetch" href="/assets/js/97.4c8c6fba.js"><link rel="prefetch" href="/assets/js/98.f9ef7bdb.js"><link rel="prefetch" href="/assets/js/vendors~docsearch.49ad9c45.js">
    <link rel="stylesheet" href="/assets/css/0.styles.af3770e9.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/en/" class="home-link router-link-active"><img src="/images/icons/spring-logo.svg" alt="Spring Docs" class="logo"> <span class="site-name can-hide">Spring Docs</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/en/spring/why-spring.html" class="nav-link">
  Spring
</a></div><div class="nav-item"><a href="/en/spring-boot/getting-help.html" class="nav-link">
  Spring Boot
</a></div><div class="nav-item"><a href="/en/spring-cloud/documentation-overview.html" class="nav-link">
  Spring Cloud
</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="Others" class="dropdown-title"><span class="title">more</span> <span class="arrow down"></span></button> <button type="button" aria-label="Others" class="mobile-dropdown-title"><span class="title">more</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/en/spring-framework/overview.html" class="nav-link">
  Spring Framework
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-data/spring-data.html" class="nav-link">
  Spring Data
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-cloud-data-flow/spring-cloud-dataflow.html" class="nav-link">
  Spring Cloud Data Flow
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-security/overview.html" class="nav-link">
  Spring Security
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-for-graphql/spring-graphql.html" class="nav-link">
  Spring for GraphQL
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-session/_index.html" class="nav-link">
  Spring Session
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-integration/preface.html" class="nav-link">
  Spring Integration
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-hateoas/spring-hateoas.html" class="nav-link">
  Spring HATEOAS
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-rest-docs/spring-restdocs.html" class="nav-link">
  Spring REST Docs
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-batch/spring-batch-intro.html" class="nav-link">
  Spring Batch
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-amqp/spring-amqp.html" class="nav-link">
  Spring AMQP
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-credhub/spring-credhub.html" class="nav-link">
  Spring CredHub
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-flo/spring-flo.html" class="nav-link">
  Spring Flo
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-for-apache-kafka/spring-kafka.html" class="nav-link">
  Spring for Apache Kafka
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-ldap/spring-ldap.html" class="nav-link">
  Spring LDAP
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-shell/spring-shell.html" class="nav-link">
  Spring Shell
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-statemachine/spring-statemachine.html" class="nav-link">
  Spring Statemachine
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-vault/spring-vault.html" class="nav-link">
  Spring Vault
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-web-flow/preface.html" class="nav-link">
  Spring Web Flow
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-web-services/spring-web-service.html" class="nav-link">
  Spring Web Services
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="Select language" class="dropdown-title"><span class="title">Language</span> <span class="arrow down"></span></button> <button type="button" aria-label="Select language" class="mobile-dropdown-title"><span class="title">Language</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/en/spring-framework/testing.html" aria-current="page" class="nav-link router-link-exact-active router-link-active">
  English
</a></li><li class="dropdown-item"><!----> <a href="/spring-framework/testing.html" class="nav-link">
  简体中文
</a></li></ul></div></div> <a href="https://gitcode.net/dev-cloud/spring-docs" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitCode
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/en/spring/why-spring.html" class="nav-link">
  Spring
</a></div><div class="nav-item"><a href="/en/spring-boot/getting-help.html" class="nav-link">
  Spring Boot
</a></div><div class="nav-item"><a href="/en/spring-cloud/documentation-overview.html" class="nav-link">
  Spring Cloud
</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="Others" class="dropdown-title"><span class="title">more</span> <span class="arrow down"></span></button> <button type="button" aria-label="Others" class="mobile-dropdown-title"><span class="title">more</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/en/spring-framework/overview.html" class="nav-link">
  Spring Framework
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-data/spring-data.html" class="nav-link">
  Spring Data
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-cloud-data-flow/spring-cloud-dataflow.html" class="nav-link">
  Spring Cloud Data Flow
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-security/overview.html" class="nav-link">
  Spring Security
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-for-graphql/spring-graphql.html" class="nav-link">
  Spring for GraphQL
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-session/_index.html" class="nav-link">
  Spring Session
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-integration/preface.html" class="nav-link">
  Spring Integration
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-hateoas/spring-hateoas.html" class="nav-link">
  Spring HATEOAS
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-rest-docs/spring-restdocs.html" class="nav-link">
  Spring REST Docs
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-batch/spring-batch-intro.html" class="nav-link">
  Spring Batch
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-amqp/spring-amqp.html" class="nav-link">
  Spring AMQP
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-credhub/spring-credhub.html" class="nav-link">
  Spring CredHub
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-flo/spring-flo.html" class="nav-link">
  Spring Flo
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-for-apache-kafka/spring-kafka.html" class="nav-link">
  Spring for Apache Kafka
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-ldap/spring-ldap.html" class="nav-link">
  Spring LDAP
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-shell/spring-shell.html" class="nav-link">
  Spring Shell
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-statemachine/spring-statemachine.html" class="nav-link">
  Spring Statemachine
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-vault/spring-vault.html" class="nav-link">
  Spring Vault
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-web-flow/preface.html" class="nav-link">
  Spring Web Flow
</a></li><li class="dropdown-item"><!----> <a href="/en/spring-web-services/spring-web-service.html" class="nav-link">
  Spring Web Services
</a></li></ul></div></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="Select language" class="dropdown-title"><span class="title">Language</span> <span class="arrow down"></span></button> <button type="button" aria-label="Select language" class="mobile-dropdown-title"><span class="title">Language</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/en/spring-framework/testing.html" aria-current="page" class="nav-link router-link-exact-active router-link-active">
  English
</a></li><li class="dropdown-item"><!----> <a href="/spring-framework/testing.html" class="nav-link">
  简体中文
</a></li></ul></div></div> <a href="https://gitcode.net/dev-cloud/spring-docs" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitCode
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav>  <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span>Spring Framework</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/en/spring-framework/overview.html" class="sidebar-link">Spring Framework Overview</a></li><li><a href="/en/spring-framework/core.html" class="sidebar-link">Core Technologies</a></li><li><a href="/en/spring-framework/testing.html" aria-current="page" class="active sidebar-link">Testing</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_1-introduction-to-spring-testing" class="sidebar-link">1. Introduction to Spring Testing</a></li><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_2-unit-testing" class="sidebar-link">2. Unit Testing</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_2-1-mock-objects" class="sidebar-link">2.1. Mock Objects</a></li><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_2-2-unit-testing-support-classes" class="sidebar-link">2.2. Unit Testing Support Classes</a></li></ul></li><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_3-integration-testing" class="sidebar-link">3. Integration Testing</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_3-1-overview" class="sidebar-link">3.1. Overview</a></li><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_3-2-goals-of-integration-testing" class="sidebar-link">3.2. Goals of Integration Testing</a></li><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_3-3-jdbc-testing-support" class="sidebar-link">3.3. JDBC Testing Support</a></li><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_3-4-annotations" class="sidebar-link">3.4. Annotations</a></li><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_3-5-spring-testcontext-framework" class="sidebar-link">3.5. Spring TestContext Framework</a></li><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_3-6-webtestclient" class="sidebar-link">3.6. WebTestClient</a></li><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_3-7-mockmvc" class="sidebar-link">3.7. MockMvc</a></li><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_3-8-testing-client-applications" class="sidebar-link">3.8. Testing Client Applications</a></li></ul></li><li class="sidebar-sub-header"><a href="/en/spring-framework/testing.html#_4-further-resources" class="sidebar-link">4. Further Resources</a></li></ul></li><li><a href="/en/spring-framework/data-access.html" class="sidebar-link">Data Access</a></li><li><a href="/en/spring-framework/web-servlet.html" class="sidebar-link">Web on Servlet Stack</a></li><li><a href="/en/spring-framework/web-reactive.html" class="sidebar-link">Web on Reactive Stack</a></li><li><a href="/en/spring-framework/integration.html" class="sidebar-link">Integration</a></li><li><a href="/en/spring-framework/languages.html" class="sidebar-link">Language Support</a></li></ul></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="testing"><a href="#testing" class="header-anchor">#</a> Testing</h1> <p>This chapter covers Spring’s support for integration testing and best practices for unit
testing. The Spring team advocates test-driven development (TDD). The Spring team has
found that the correct use of inversion of control (IoC) certainly does make both unit
and integration testing easier (in that the presence of setter methods and appropriate
constructors on classes makes them easier to wire together in a test without having to
set up service locator registries and similar structures).</p> <h2 id="_1-introduction-to-spring-testing"><a href="#_1-introduction-to-spring-testing" class="header-anchor">#</a> 1. Introduction to Spring Testing</h2> <p>Testing is an integral part of enterprise software development. This chapter focuses on
the value added by the IoC principle to <a href="#unit-testing">unit testing</a> and on the benefits
of the Spring Framework’s support for <a href="#integration-testing">integration testing</a>. (A
thorough treatment of testing in the enterprise is beyond the scope of this reference
manual.)</p> <h2 id="_2-unit-testing"><a href="#_2-unit-testing" class="header-anchor">#</a> 2. Unit Testing</h2> <p>Dependency injection should make your code less dependent on the container than it would
be with traditional Java EE development. The POJOs that make up your application should
be testable in JUnit or TestNG tests, with objects instantiated by using the <code>new</code>operator, without Spring or any other container. You can use <a href="#mock-objects">mock objects</a>(in conjunction with other valuable testing techniques) to test your code in isolation.
If you follow the architecture recommendations for Spring, the resulting clean layering
and componentization of your codebase facilitate easier unit testing. For example,
you can test service layer objects by stubbing or mocking DAO or repository interfaces,
without needing to access persistent data while running unit tests.</p> <p>True unit tests typically run extremely quickly, as there is no runtime infrastructure to
set up. Emphasizing true unit tests as part of your development methodology can boost
your productivity. You may not need this section of the testing chapter to help you write
effective unit tests for your IoC-based applications. For certain unit testing scenarios,
however, the Spring Framework provides mock objects and testing support classes, which
are described in this chapter.</p> <h3 id="_2-1-mock-objects"><a href="#_2-1-mock-objects" class="header-anchor">#</a> 2.1. Mock Objects</h3> <p>Spring includes a number of packages dedicated to mocking:</p> <ul><li><p><a href="#mock-objects-env">Environment</a></p></li> <li><p><a href="#mock-objects-jndi">JNDI</a></p></li> <li><p><a href="#mock-objects-servlet">Servlet API</a></p></li> <li><p><a href="#mock-objects-web-reactive">Spring Web Reactive</a></p></li></ul> <h4 id="_2-1-1-environment"><a href="#_2-1-1-environment" class="header-anchor">#</a> 2.1.1. Environment</h4> <p>The <code>org.springframework.mock.env</code> package contains mock implementations of the<code>Environment</code> and <code>PropertySource</code> abstractions (see<a href="/en/spring-framework/core.html#beans-definition-profiles">Bean Definition Profiles</a>and <a href="/en/spring-framework/core.html#beans-property-source-abstraction"><code>PropertySource</code> Abstraction</a>).<code>MockEnvironment</code> and <code>MockPropertySource</code> are useful for developing
out-of-container tests for code that depends on environment-specific properties.</p> <h4 id="_2-1-2-jndi"><a href="#_2-1-2-jndi" class="header-anchor">#</a> 2.1.2. JNDI</h4> <p>The <code>org.springframework.mock.jndi</code> package contains a partial implementation of the JNDI
SPI, which you can use to set up a simple JNDI environment for test suites or stand-alone
applications. If, for example, JDBC <code>DataSource</code> instances get bound to the same JNDI
names in test code as they do in a Java EE container, you can reuse both application code
and configuration in testing scenarios without modification.</p> <table><thead><tr><th></th> <th>The mock JNDI support in the <code>org.springframework.mock.jndi</code> package is<br>officially deprecated as of Spring Framework 5.2 in favor of complete solutions from third<br>parties such as <a href="https://github.com/h-thurow/Simple-JNDI" target="_blank" rel="noopener noreferrer">Simple-JNDI<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>.</th></tr></thead> <tbody></tbody></table> <h4 id="_2-1-3-servlet-api"><a href="#_2-1-3-servlet-api" class="header-anchor">#</a> 2.1.3. Servlet API</h4> <p>The <code>org.springframework.mock.web</code> package contains a comprehensive set of Servlet API
mock objects that are useful for testing web contexts, controllers, and filters. These
mock objects are targeted at usage with Spring’s Web MVC framework and are generally more
convenient to use than dynamic mock objects (such as <a href="http://easymock.org/" target="_blank" rel="noopener noreferrer">EasyMock<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>)
or alternative Servlet API mock objects (such as <a href="http://www.mockobjects.com" target="_blank" rel="noopener noreferrer">MockObjects<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>).</p> <table><thead><tr><th></th> <th>Since Spring Framework 5.0, the mock objects in <code>org.springframework.mock.web</code> are<br>based on the Servlet 4.0 API.</th></tr></thead> <tbody></tbody></table> <p>The Spring MVC Test framework builds on the mock Servlet API objects to provide an
integration testing framework for Spring MVC. See <a href="#spring-mvc-test-framework">MockMvc</a>.</p> <h4 id="_2-1-4-spring-web-reactive"><a href="#_2-1-4-spring-web-reactive" class="header-anchor">#</a> 2.1.4. Spring Web Reactive</h4> <p>The <code>org.springframework.mock.http.server.reactive</code> package contains mock implementations
of <code>ServerHttpRequest</code> and <code>ServerHttpResponse</code> for use in WebFlux applications. The<code>org.springframework.mock.web.server</code> package contains a mock <code>ServerWebExchange</code> that
depends on those mock request and response objects.</p> <p>Both <code>MockServerHttpRequest</code> and <code>MockServerHttpResponse</code> extend from the same abstract
base classes as server-specific implementations and share behavior with them. For
example, a mock request is immutable once created, but you can use the <code>mutate()</code> method
from <code>ServerHttpRequest</code> to create a modified instance.</p> <p>In order for the mock response to properly implement the write contract and return a
write completion handle (that is, <code>Mono&lt;Void&gt;</code>), it by default uses a <code>Flux</code> with<code>cache().then()</code>, which buffers the data and makes it available for assertions in tests.
Applications can set a custom write function (for example, to test an infinite stream).</p> <p>The <a href="#webtestclient">WebTestClient</a> builds on the mock request and response to provide support for
testing WebFlux applications without an HTTP server. The client can also be used for
end-to-end tests with a running server.</p> <h3 id="_2-2-unit-testing-support-classes"><a href="#_2-2-unit-testing-support-classes" class="header-anchor">#</a> 2.2. Unit Testing Support Classes</h3> <p>Spring includes a number of classes that can help with unit testing. They fall into two
categories:</p> <ul><li><p><a href="#unit-testing-utilities">General Testing Utilities</a></p></li> <li><p><a href="#unit-testing-spring-mvc">Spring MVC Testing Utilities</a></p></li></ul> <h4 id="_2-2-1-general-testing-utilities"><a href="#_2-2-1-general-testing-utilities" class="header-anchor">#</a> 2.2.1. General Testing Utilities</h4> <p>The <code>org.springframework.test.util</code> package contains several general purpose utilities
for use in unit and integration testing.</p> <p><code>ReflectionTestUtils</code> is a collection of reflection-based utility methods. You can use
these methods in testing scenarios where you need to change the value of a constant, set
a non-<code>public</code> field, invoke a non-<code>public</code> setter method, or invoke a non-<code>public</code>configuration or lifecycle callback method when testing application code for use cases
such as the following:</p> <ul><li><p>ORM frameworks (such as JPA and Hibernate) that condone <code>private</code> or <code>protected</code> field
access as opposed to <code>public</code> setter methods for properties in a domain entity.</p></li> <li><p>Spring’s support for annotations (such as <code>@Autowired</code>, <code>@Inject</code>, and <code>@Resource</code>),
that provide dependency injection for <code>private</code> or <code>protected</code> fields, setter methods,
and configuration methods.</p></li> <li><p>Use of annotations such as <code>@PostConstruct</code> and <code>@PreDestroy</code> for lifecycle callback
methods.</p></li></ul> <p><a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/util/AopTestUtils.html" target="_blank" rel="noopener noreferrer"><code>AopTestUtils</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> is a collection of
AOP-related utility methods. You can use these methods to obtain a reference to the
underlying target object hidden behind one or more Spring proxies. For example, if you
have configured a bean as a dynamic mock by using a library such as EasyMock or Mockito,
and the mock is wrapped in a Spring proxy, you may need direct access to the underlying
mock to configure expectations on it and perform verifications. For Spring’s core AOP
utilities, see <a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/aop/support/AopUtils.html" target="_blank" rel="noopener noreferrer"><code>AopUtils</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> and<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/aop/framework/AopProxyUtils.html" target="_blank" rel="noopener noreferrer"><code>AopProxyUtils</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>.</p> <h4 id="_2-2-2-spring-mvc-testing-utilities"><a href="#_2-2-2-spring-mvc-testing-utilities" class="header-anchor">#</a> 2.2.2. Spring MVC Testing Utilities</h4> <p>The <code>org.springframework.test.web</code> package contains<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/web/ModelAndViewAssert.html" target="_blank" rel="noopener noreferrer"><code>ModelAndViewAssert</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>, which you
can use in combination with JUnit, TestNG, or any other testing framework for unit tests
that deal with Spring MVC <code>ModelAndView</code> objects.</p> <table><thead><tr><th></th> <th>Unit testing Spring MVC Controllers<br><br>To unit test your Spring MVC <code>Controller</code> classes as POJOs, use <code>ModelAndViewAssert</code>combined with <code>MockHttpServletRequest</code>, <code>MockHttpSession</code>, and so on from Spring’s<a href="#mock-objects-servlet">Servlet API mocks</a>. For thorough integration testing of your<br>Spring MVC and REST <code>Controller</code> classes in conjunction with your <code>WebApplicationContext</code>configuration for Spring MVC, use the<a href="#spring-mvc-test-framework">Spring MVC Test Framework</a> instead.</th></tr></thead> <tbody></tbody></table> <h2 id="_3-integration-testing"><a href="#_3-integration-testing" class="header-anchor">#</a> 3. Integration Testing</h2> <p>This section (most of the rest of this chapter) covers integration testing for Spring
applications. It includes the following topics:</p> <ul><li><p><a href="#integration-testing-overview">Overview</a></p></li> <li><p><a href="#integration-testing-goals">Goals of Integration Testing</a></p></li> <li><p><a href="#integration-testing-support-jdbc">JDBC Testing Support</a></p></li> <li><p><a href="#integration-testing-annotations">Annotations</a></p></li> <li><p><a href="#testcontext-framework">Spring TestContext Framework</a></p></li> <li><p><a href="#spring-mvc-test-framework">MockMvc</a></p></li></ul> <h3 id="_3-1-overview"><a href="#_3-1-overview" class="header-anchor">#</a> 3.1. Overview</h3> <p>It is important to be able to perform some integration testing without requiring
deployment to your application server or connecting to other enterprise infrastructure.
Doing so lets you test things such as:</p> <ul><li><p>The correct wiring of your Spring IoC container contexts.</p></li> <li><p>Data access using JDBC or an ORM tool. This can include such things as the correctness
of SQL statements, Hibernate queries, JPA entity mappings, and so forth.</p></li></ul> <p>The Spring Framework provides first-class support for integration testing in the<code>spring-test</code> module. The name of the actual JAR file might include the release version
and might also be in the long <code>org.springframework.test</code> form, depending on where you get
it from (see the <a href="/en/spring-framework/core.html#dependency-management">section on Dependency Management</a>for an explanation). This library includes the <code>org.springframework.test</code> package, which
contains valuable classes for integration testing with a Spring container. This testing
does not rely on an application server or other deployment environment. Such tests are
slower to run than unit tests but much faster than the equivalent Selenium tests or
remote tests that rely on deployment to an application server.</p> <p>Unit and integration testing support is provided in the form of the annotation-driven<a href="#testcontext-framework">Spring TestContext Framework</a>. The TestContext framework is
agnostic of the actual testing framework in use, which allows instrumentation of tests
in various environments, including JUnit, TestNG, and others.</p> <h3 id="_3-2-goals-of-integration-testing"><a href="#_3-2-goals-of-integration-testing" class="header-anchor">#</a> 3.2. Goals of Integration Testing</h3> <p>Spring’s integration testing support has the following primary goals:</p> <ul><li><p>To manage <a href="#testing-ctx-management">Spring IoC container caching</a> between tests.</p></li> <li><p>To provide <a href="#testing-fixture-di">Dependency Injection of test fixture instances</a>.</p></li> <li><p>To provide <a href="#testing-tx">transaction management</a> appropriate to integration testing.</p></li> <li><p>To supply <a href="#testing-support-classes">Spring-specific base classes</a> that assist
developers in writing integration tests.</p></li></ul> <p>The next few sections describe each goal and provide links to implementation and
configuration details.</p> <h4 id="_3-2-1-context-management-and-caching"><a href="#_3-2-1-context-management-and-caching" class="header-anchor">#</a> 3.2.1. Context Management and Caching</h4> <p>The Spring TestContext Framework provides consistent loading of Spring<code>ApplicationContext</code> instances and <code>WebApplicationContext</code> instances as well as caching
of those contexts. Support for the caching of loaded contexts is important, because
startup time can become an issue — not because of the overhead of Spring itself, but
because the objects instantiated by the Spring container take time to instantiate. For
example, a project with 50 to 100 Hibernate mapping files might take 10 to 20 seconds to
load the mapping files, and incurring that cost before running every test in every test
fixture leads to slower overall test runs that reduce developer productivity.</p> <p>Test classes typically declare either an array of resource locations for XML or Groovy
configuration metadata — often in the classpath — or an array of component classes that
is used to configure the application. These locations or classes are the same as or
similar to those specified in <code>web.xml</code> or other configuration files for production
deployments.</p> <p>By default, once loaded, the configured <code>ApplicationContext</code> is reused for each test.
Thus, the setup cost is incurred only once per test suite, and subsequent test execution
is much faster. In this context, the term “test suite” means all tests run in the same
JVM — for example, all tests run from an Ant, Maven, or Gradle build for a given project
or module. In the unlikely case that a test corrupts the application context and requires
reloading (for example, by modifying a bean definition or the state of an application
object) the TestContext framework can be configured to reload the configuration and
rebuild the application context before executing the next test.</p> <p>See <a href="#testcontext-ctx-management">Context Management</a> and <a href="#testcontext-ctx-management-caching">Context Caching</a> with the
TestContext framework.</p> <h4 id="_3-2-2-dependency-injection-of-test-fixtures"><a href="#_3-2-2-dependency-injection-of-test-fixtures" class="header-anchor">#</a> 3.2.2. Dependency Injection of Test Fixtures</h4> <p>When the TestContext framework loads your application context, it can optionally
configure instances of your test classes by using Dependency Injection. This provides a
convenient mechanism for setting up test fixtures by using preconfigured beans from your
application context. A strong benefit here is that you can reuse application contexts
across various testing scenarios (for example, for configuring Spring-managed object
graphs, transactional proxies, <code>DataSource</code> instances, and others), thus avoiding the
need to duplicate complex test fixture setup for individual test cases.</p> <p>As an example, consider a scenario where we have a class (<code>HibernateTitleRepository</code>)
that implements data access logic for a <code>Title</code> domain entity. We want to write
integration tests that test the following areas:</p> <ul><li><p>The Spring configuration: Basically, is everything related to the configuration of the<code>HibernateTitleRepository</code> bean correct and present?</p></li> <li><p>The Hibernate mapping file configuration: Is everything mapped correctly and are the
correct lazy-loading settings in place?</p></li> <li><p>The logic of the <code>HibernateTitleRepository</code>: Does the configured instance of this class
perform as anticipated?</p></li></ul> <p>See dependency injection of test fixtures with the<a href="#testcontext-fixture-di">TestContext framework</a>.</p> <h4 id="_3-2-3-transaction-management"><a href="#_3-2-3-transaction-management" class="header-anchor">#</a> 3.2.3. Transaction Management</h4> <p>One common issue in tests that access a real database is their effect on the state of the
persistence store. Even when you use a development database, changes to the state may
affect future tests. Also, many operations — such as inserting or modifying persistent
data — cannot be performed (or verified) outside of a transaction.</p> <p>The TestContext framework addresses this issue. By default, the framework creates and
rolls back a transaction for each test. You can write code that can assume the existence
of a transaction. If you call transactionally proxied objects in your tests, they behave
correctly, according to their configured transactional semantics. In addition, if a test
method deletes the contents of selected tables while running within the transaction
managed for the test, the transaction rolls back by default, and the database returns to
its state prior to execution of the test. Transactional support is provided to a test by
using a <code>PlatformTransactionManager</code> bean defined in the test’s application context.</p> <p>If you want a transaction to commit (unusual, but occasionally useful when you want a
particular test to populate or modify the database), you can tell the TestContext
framework to cause the transaction to commit instead of roll back by using the<a href="#integration-testing-annotations"><code>@Commit</code></a> annotation.</p> <p>See transaction management with the <a href="#testcontext-tx">TestContext framework</a>.</p> <h4 id="_3-2-4-support-classes-for-integration-testing"><a href="#_3-2-4-support-classes-for-integration-testing" class="header-anchor">#</a> 3.2.4. Support Classes for Integration Testing</h4> <p>The Spring TestContext Framework provides several <code>abstract</code> support classes that
simplify the writing of integration tests. These base test classes provide well-defined
hooks into the testing framework as well as convenient instance variables and methods,
which let you access:</p> <ul><li><p>The <code>ApplicationContext</code>, for performing explicit bean lookups or testing the state of
the context as a whole.</p></li> <li><p>A <code>JdbcTemplate</code>, for executing SQL statements to query the database. You can use such
queries to confirm database state both before and after execution of database-related
application code, and Spring ensures that such queries run in the scope of the same
transaction as the application code. When used in conjunction with an ORM tool, be sure
to avoid <a href="#testcontext-tx-false-positives">false positives</a>.</p></li></ul> <p>In addition, you may want to create your own custom, application-wide superclass with
instance variables and methods specific to your project.</p> <p>See support classes for the <a href="#testcontext-support-classes">TestContext framework</a>.</p> <h3 id="_3-3-jdbc-testing-support"><a href="#_3-3-jdbc-testing-support" class="header-anchor">#</a> 3.3. JDBC Testing Support</h3> <p>The <code>org.springframework.test.jdbc</code> package contains <code>JdbcTestUtils</code>, which is a
collection of JDBC-related utility functions intended to simplify standard database
testing scenarios. Specifically, <code>JdbcTestUtils</code> provides the following static utility
methods.</p> <ul><li><p><code>countRowsInTable(..)</code>: Counts the number of rows in the given table.</p></li> <li><p><code>countRowsInTableWhere(..)</code>: Counts the number of rows in the given table by using the
provided <code>WHERE</code> clause.</p></li> <li><p><code>deleteFromTables(..)</code>: Deletes all rows from the specified tables.</p></li> <li><p><code>deleteFromTableWhere(..)</code>: Deletes rows from the given table by using the provided<code>WHERE</code> clause.</p></li> <li><p><code>dropTables(..)</code>: Drops the specified tables.</p></li></ul> <table><thead><tr><th></th> <th><a href="#testcontext-support-classes-junit4"><code>AbstractTransactionalJUnit4SpringContextTests</code></a>and <a href="#testcontext-support-classes-testng"><code>AbstractTransactionalTestNGSpringContextTests</code></a>provide convenience methods that delegate to the aforementioned methods in<code>JdbcTestUtils</code>.<br><br>The <code>spring-jdbc</code> module provides support for configuring and launching an embedded<br>database, which you can use in integration tests that interact with a database.<br>For details, see <a href="/en/spring-framework/data-access.html#jdbc-embedded-database-support">Embedded Database<br>Support</a> and <a href="/en/spring-framework/data-access.html#jdbc-embedded-database-dao-testing">Testing Data Access<br>Logic with an Embedded Database</a>.</th></tr></thead> <tbody></tbody></table> <h3 id="_3-4-annotations"><a href="#_3-4-annotations" class="header-anchor">#</a> 3.4. Annotations</h3> <p>This section covers annotations that you can use when you test Spring applications.
It includes the following topics:</p> <ul><li><p><a href="#integration-testing-annotations-spring">Spring Testing Annotations</a></p></li> <li><p><a href="#integration-testing-annotations-standard">Standard Annotation Support</a></p></li> <li><p><a href="#integration-testing-annotations-junit4">Spring JUnit 4 Testing Annotations</a></p></li> <li><p><a href="#integration-testing-annotations-junit-jupiter">Spring JUnit Jupiter Testing Annotations</a></p></li> <li><p><a href="#integration-testing-annotations-meta">Meta-Annotation Support for Testing</a></p></li></ul> <h4 id="_3-4-1-spring-testing-annotations"><a href="#_3-4-1-spring-testing-annotations" class="header-anchor">#</a> 3.4.1. Spring Testing Annotations</h4> <p>The Spring Framework provides the following set of Spring-specific annotations that you
can use in your unit and integration tests in conjunction with the TestContext framework.
See the corresponding javadoc for further information, including default attribute
values, attribute aliases, and other details.</p> <p>Spring’s testing annotations include the following:</p> <ul><li><p><a href="#spring-testing-annotation-bootstrapwith"><code>@BootstrapWith</code></a></p></li> <li><p><a href="#spring-testing-annotation-contextconfiguration"><code>@ContextConfiguration</code></a></p></li> <li><p><a href="#spring-testing-annotation-webappconfiguration"><code>@WebAppConfiguration</code></a></p></li> <li><p><a href="#spring-testing-annotation-contexthierarchy"><code>@ContextHierarchy</code></a></p></li> <li><p><a href="#spring-testing-annotation-activeprofiles"><code>@ActiveProfiles</code></a></p></li> <li><p><a href="#spring-testing-annotation-testpropertysource"><code>@TestPropertySource</code></a></p></li> <li><p><a href="#spring-testing-annotation-dynamicpropertysource"><code>@DynamicPropertySource</code></a></p></li> <li><p><a href="#spring-testing-annotation-dirtiescontext"><code>@DirtiesContext</code></a></p></li> <li><p><a href="#spring-testing-annotation-testexecutionlisteners"><code>@TestExecutionListeners</code></a></p></li> <li><p><a href="#spring-testing-annotation-recordapplicationevents"><code>@RecordApplicationEvents</code></a></p></li> <li><p><a href="#spring-testing-annotation-commit"><code>@Commit</code></a></p></li> <li><p><a href="#spring-testing-annotation-rollback"><code>@Rollback</code></a></p></li> <li><p><a href="#spring-testing-annotation-beforetransaction"><code>@BeforeTransaction</code></a></p></li> <li><p><a href="#spring-testing-annotation-aftertransaction"><code>@AfterTransaction</code></a></p></li> <li><p><a href="#spring-testing-annotation-sql"><code>@Sql</code></a></p></li> <li><p><a href="#spring-testing-annotation-sqlconfig"><code>@SqlConfig</code></a></p></li> <li><p><a href="#spring-testing-annotation-sqlmergemode"><code>@SqlMergeMode</code></a></p></li> <li><p><a href="#spring-testing-annotation-sqlgroup"><code>@SqlGroup</code></a></p></li></ul> <h5 id="bootstrapwith"><a href="#bootstrapwith" class="header-anchor">#</a> <code>@BootstrapWith</code></h5> <p><code>@BootstrapWith</code> is a class-level annotation that you can use to configure how the Spring
TestContext Framework is bootstrapped. Specifically, you can use <code>@BootstrapWith</code> to
specify a custom <code>TestContextBootstrapper</code>. See the section on<a href="#testcontext-bootstrapping">bootstrapping the TestContext framework</a> for further details.</p> <h5 id="contextconfiguration"><a href="#contextconfiguration" class="header-anchor">#</a> <code>@ContextConfiguration</code></h5> <p><code>@ContextConfiguration</code> defines class-level metadata that is used to determine how to
load and configure an <code>ApplicationContext</code> for integration tests. Specifically,<code>@ContextConfiguration</code> declares the application context resource <code>locations</code> or the
component <code>classes</code> used to load the context.</p> <p>Resource locations are typically XML configuration files or Groovy scripts located in the
classpath, while component classes are typically <code>@Configuration</code> classes. However,
resource locations can also refer to files and scripts in the file system, and component
classes can be <code>@Component</code> classes, <code>@Service</code> classes, and so on. See<a href="#testcontext-ctx-management-javaconfig-component-classes">Component Classes</a> for further details.</p> <p>The following example shows a <code>@ContextConfiguration</code> annotation that refers to an XML
file:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration(&quot;/test-config.xml&quot;) (1)
class XmlApplicationContextTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Referring to an XML file.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration(&quot;/test-config.xml&quot;) (1)
class XmlApplicationContextTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Referring to an XML file.</th></tr></thead> <tbody></tbody></table> <p>The following example shows a <code>@ContextConfiguration</code> annotation that refers to a class:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration(classes = TestConfig.class) (1)
class ConfigClassApplicationContextTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Referring to a class.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration(classes = [TestConfig::class]) (1)
class ConfigClassApplicationContextTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Referring to a class.</th></tr></thead> <tbody></tbody></table> <p>As an alternative or in addition to declaring resource locations or component classes,
you can use <code>@ContextConfiguration</code> to declare <code>ApplicationContextInitializer</code> classes.
The following example shows such a case:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration(initializers = CustomContextIntializer.class) (1)
class ContextInitializerTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Declaring an initializer class.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration(initializers = [CustomContextIntializer::class]) (1)
class ContextInitializerTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Declaring an initializer class.</th></tr></thead> <tbody></tbody></table> <p>You can optionally use <code>@ContextConfiguration</code> to declare the <code>ContextLoader</code> strategy as
well. Note, however, that you typically do not need to explicitly configure the loader,
since the default loader supports <code>initializers</code> and either resource <code>locations</code> or
component <code>classes</code>.</p> <p>The following example uses both a location and a loader:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration(locations = &quot;/test-context.xml&quot;, loader = CustomContextLoader.class) (1)
class CustomLoaderXmlApplicationContextTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Configuring both a location and a custom loader.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration(&quot;/test-context.xml&quot;, loader = CustomContextLoader::class) (1)
class CustomLoaderXmlApplicationContextTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Configuring both a location and a custom loader.</th></tr></thead> <tbody></tbody></table> <table><thead><tr><th></th> <th><code>@ContextConfiguration</code> provides support for inheriting resource locations or<br>configuration classes as well as context initializers that are declared by superclasses<br>or enclosing classes.</th></tr></thead> <tbody></tbody></table> <p>See <a href="#testcontext-ctx-management">Context Management</a>,<a href="#testcontext-junit-jupiter-nested-test-configuration"><code>@Nested</code> test class configuration</a>, and the <code>@ContextConfiguration</code>javadocs for further details.</p> <h5 id="webappconfiguration"><a href="#webappconfiguration" class="header-anchor">#</a> <code>@WebAppConfiguration</code></h5> <p><code>@WebAppConfiguration</code> is a class-level annotation that you can use to declare that the<code>ApplicationContext</code> loaded for an integration test should be a <code>WebApplicationContext</code>.
The mere presence of <code>@WebAppConfiguration</code> on a test class ensures that a<code>WebApplicationContext</code> is loaded for the test, using the default value of<code>&quot;file:src/main/webapp&quot;</code> for the path to the root of the web application (that is, the
resource base path). The resource base path is used behind the scenes to create a<code>MockServletContext</code>, which serves as the <code>ServletContext</code> for the test’s<code>WebApplicationContext</code>.</p> <p>The following example shows how to use the <code>@WebAppConfiguration</code> annotation:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@WebAppConfiguration (1)
class WebAppTests {
    // class body...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@WebAppConfiguration (1)
class WebAppTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>The <code>@WebAppConfiguration</code> annotation.</th></tr></thead> <tbody></tbody></table> <p>To override the default, you can specify a different base resource path by using the
implicit <code>value</code> attribute. Both <code>classpath:</code> and <code>file:</code> resource prefixes are
supported. If no resource prefix is supplied, the path is assumed to be a file system
resource. The following example shows how to specify a classpath resource:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@WebAppConfiguration(&quot;classpath:test-web-resources&quot;) (1)
class WebAppTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying a classpath resource.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@WebAppConfiguration(&quot;classpath:test-web-resources&quot;) (1)
class WebAppTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying a classpath resource.</th></tr></thead> <tbody></tbody></table> <p>Note that <code>@WebAppConfiguration</code> must be used in conjunction with<code>@ContextConfiguration</code>, either within a single test class or within a test class
hierarchy. See the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/web/WebAppConfiguration.html" target="_blank" rel="noopener noreferrer"><code>@WebAppConfiguration</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>javadoc for further details.</p> <h5 id="contexthierarchy"><a href="#contexthierarchy" class="header-anchor">#</a> <code>@ContextHierarchy</code></h5> <p><code>@ContextHierarchy</code> is a class-level annotation that is used to define a hierarchy of<code>ApplicationContext</code> instances for integration tests. <code>@ContextHierarchy</code> should be
declared with a list of one or more <code>@ContextConfiguration</code> instances, each of which
defines a level in the context hierarchy. The following examples demonstrate the use of<code>@ContextHierarchy</code> within a single test class (<code>@ContextHierarchy</code> can also be used
within a test class hierarchy):</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextHierarchy({
    @ContextConfiguration(&quot;/parent-config.xml&quot;),
    @ContextConfiguration(&quot;/child-config.xml&quot;)
})
class ContextHierarchyTests {
    // class body...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextHierarchy(
    ContextConfiguration(&quot;/parent-config.xml&quot;),
    ContextConfiguration(&quot;/child-config.xml&quot;))
class ContextHierarchyTests {
    // class body...
}
</code></pre></div><p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@WebAppConfiguration
@ContextHierarchy({
    @ContextConfiguration(classes = AppConfig.class),
    @ContextConfiguration(classes = WebConfig.class)
})
class WebIntegrationTests {
    // class body...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@WebAppConfiguration
@ContextHierarchy(
        ContextConfiguration(classes = [AppConfig::class]),
        ContextConfiguration(classes = [WebConfig::class]))
class WebIntegrationTests {
    // class body...
}
</code></pre></div><p>If you need to merge or override the configuration for a given level of the context
hierarchy within a test class hierarchy, you must explicitly name that level by supplying
the same value to the <code>name</code> attribute in <code>@ContextConfiguration</code> at each corresponding
level in the class hierarchy. See <a href="#testcontext-ctx-management-ctx-hierarchies">Context Hierarchies</a> and the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/ContextHierarchy.html" target="_blank" rel="noopener noreferrer"><code>@ContextHierarchy</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> javadoc
for further examples.</p> <h5 id="activeprofiles"><a href="#activeprofiles" class="header-anchor">#</a> <code>@ActiveProfiles</code></h5> <p><code>@ActiveProfiles</code> is a class-level annotation that is used to declare which bean
definition profiles should be active when loading an <code>ApplicationContext</code> for an
integration test.</p> <p>The following example indicates that the <code>dev</code> profile should be active:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@ActiveProfiles(&quot;dev&quot;) (1)
class DeveloperTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Indicate that the <code>dev</code> profile should be active.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@ActiveProfiles(&quot;dev&quot;) (1)
class DeveloperTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Indicate that the <code>dev</code> profile should be active.</th></tr></thead> <tbody></tbody></table> <p>The following example indicates that both the <code>dev</code> and the <code>integration</code> profiles should
be active:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@ActiveProfiles({&quot;dev&quot;, &quot;integration&quot;}) (1)
class DeveloperIntegrationTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Indicate that the <code>dev</code> and <code>integration</code> profiles should be active.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@ActiveProfiles([&quot;dev&quot;, &quot;integration&quot;]) (1)
class DeveloperIntegrationTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Indicate that the <code>dev</code> and <code>integration</code> profiles should be active.</th></tr></thead> <tbody></tbody></table> <table><thead><tr><th></th> <th><code>@ActiveProfiles</code> provides support for inheriting active bean definition profiles<br>declared by superclasses and enclosing classes by default. You can also resolve active<br>bean definition profiles programmatically by implementing a custom<a href="#testcontext-ctx-management-env-profiles-ActiveProfilesResolver"><code>ActiveProfilesResolver</code></a>and registering it by using the <code>resolver</code> attribute of <code>@ActiveProfiles</code>.</th></tr></thead> <tbody></tbody></table> <p>See <a href="#testcontext-ctx-management-env-profiles">Context Configuration with Environment Profiles</a>,<a href="#testcontext-junit-jupiter-nested-test-configuration"><code>@Nested</code> test class configuration</a>, and the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/ActiveProfiles.html" target="_blank" rel="noopener noreferrer"><code>@ActiveProfiles</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> javadoc for
examples and further details.</p> <h5 id="testpropertysource"><a href="#testpropertysource" class="header-anchor">#</a> <code>@TestPropertySource</code></h5> <p><code>@TestPropertySource</code> is a class-level annotation that you can use to configure the
locations of properties files and inlined properties to be added to the set of<code>PropertySources</code> in the <code>Environment</code> for an <code>ApplicationContext</code> loaded for an
integration test.</p> <p>The following example demonstrates how to declare a properties file from the classpath:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestPropertySource(&quot;/test.properties&quot;) (1)
class MyIntegrationTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Get properties from <code>test.properties</code> in the root of the classpath.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestPropertySource(&quot;/test.properties&quot;) (1)
class MyIntegrationTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Get properties from <code>test.properties</code> in the root of the classpath.</th></tr></thead> <tbody></tbody></table> <p>The following example demonstrates how to declare inlined properties:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestPropertySource(properties = { &quot;timezone = GMT&quot;, &quot;port: 4242&quot; }) (1)
class MyIntegrationTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Declare <code>timezone</code> and <code>port</code> properties.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestPropertySource(properties = [&quot;timezone = GMT&quot;, &quot;port: 4242&quot;]) (1)
class MyIntegrationTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Declare <code>timezone</code> and <code>port</code> properties.</th></tr></thead> <tbody></tbody></table> <p>See <a href="#testcontext-ctx-management-property-sources">Context Configuration with Test Property Sources</a> for examples and further details.</p> <h5 id="dynamicpropertysource"><a href="#dynamicpropertysource" class="header-anchor">#</a> <code>@DynamicPropertySource</code></h5> <p><code>@DynamicPropertySource</code> is a method-level annotation that you can use to register<em>dynamic</em> properties to be added to the set of <code>PropertySources</code> in the <code>Environment</code> for
an <code>ApplicationContext</code> loaded for an integration test. Dynamic properties are useful
when you do not know the value of the properties upfront – for example, if the properties
are managed by an external resource such as for a container managed by the<a href="https://www.testcontainers.org/" target="_blank" rel="noopener noreferrer">Testcontainers<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> project.</p> <p>The following example demonstrates how to register a dynamic property:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
class MyIntegrationTests {

    static MyExternalServer server = // ...

    @DynamicPropertySource (1)
    static void dynamicProperties(DynamicPropertyRegistry registry) { (2)
        registry.add(&quot;server.port&quot;, server::getPort); (3)
    }

    // tests ...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Annotate a <code>static</code> method with <code>@DynamicPropertySource</code>.</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Accept a <code>DynamicPropertyRegistry</code> as an argument.</td></tr> <tr><td><strong>3</strong></td> <td>Register a dynamic <code>server.port</code> property to be retrieved lazily from the server.</td></tr></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
class MyIntegrationTests {

    companion object {

        @JvmStatic
        val server: MyExternalServer = // ...

        @DynamicPropertySource (1)
        @JvmStatic
        fun dynamicProperties(registry: DynamicPropertyRegistry) { (2)
            registry.add(&quot;server.port&quot;, server::getPort) (3)
        }
    }

    // tests ...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Annotate a <code>static</code> method with <code>@DynamicPropertySource</code>.</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Accept a <code>DynamicPropertyRegistry</code> as an argument.</td></tr> <tr><td><strong>3</strong></td> <td>Register a dynamic <code>server.port</code> property to be retrieved lazily from the server.</td></tr></tbody></table> <p>See <a href="#testcontext-ctx-management-dynamic-property-sources">Context Configuration with Dynamic Property Sources</a> for further details.</p> <h5 id="dirtiescontext"><a href="#dirtiescontext" class="header-anchor">#</a> <code>@DirtiesContext</code></h5> <p><code>@DirtiesContext</code> indicates that the underlying Spring <code>ApplicationContext</code> has been
dirtied during the execution of a test (that is, the test modified or corrupted it in
some manner — for example, by changing the state of a singleton bean) and should be
closed. When an application context is marked as dirty, it is removed from the testing
framework’s cache and closed. As a consequence, the underlying Spring container is
rebuilt for any subsequent test that requires a context with the same configuration
metadata.</p> <p>You can use <code>@DirtiesContext</code> as both a class-level and a method-level annotation within
the same class or class hierarchy. In such scenarios, the <code>ApplicationContext</code> is marked
as dirty before or after any such annotated method as well as before or after the current
test class, depending on the configured <code>methodMode</code> and <code>classMode</code>.</p> <p>The following examples explain when the context would be dirtied for various
configuration scenarios:</p> <ul><li><p>Before the current test class, when declared on a class with class mode set to<code>BEFORE_CLASS</code>.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@DirtiesContext(classMode = BEFORE_CLASS) (1)
class FreshContextTests {
    // some tests that require a new Spring container
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Dirty the context before the current test class.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@DirtiesContext(classMode = BEFORE_CLASS) (1)
class FreshContextTests {
    // some tests that require a new Spring container
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Dirty the context before the current test class.</th></tr></thead> <tbody></tbody></table></li> <li><p>After the current test class, when declared on a class with class mode set to<code>AFTER_CLASS</code> (i.e., the default class mode).</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@DirtiesContext (1)
class ContextDirtyingTests {
    // some tests that result in the Spring container being dirtied
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Dirty the context after the current test class.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@DirtiesContext (1)
class ContextDirtyingTests {
    // some tests that result in the Spring container being dirtied
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Dirty the context after the current test class.</th></tr></thead> <tbody></tbody></table></li> <li><p>Before each test method in the current test class, when declared on a class with class
mode set to <code>BEFORE_EACH_TEST_METHOD.</code></p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@DirtiesContext(classMode = BEFORE_EACH_TEST_METHOD) (1)
class FreshContextTests {
    // some tests that require a new Spring container
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Dirty the context before each test method.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@DirtiesContext(classMode = BEFORE_EACH_TEST_METHOD) (1)
class FreshContextTests {
    // some tests that require a new Spring container
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Dirty the context before each test method.</th></tr></thead> <tbody></tbody></table></li> <li><p>After each test method in the current test class, when declared on a class with class
mode set to <code>AFTER_EACH_TEST_METHOD.</code></p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) (1)
class ContextDirtyingTests {
    // some tests that result in the Spring container being dirtied
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Dirty the context after each test method.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) (1)
class ContextDirtyingTests {
    // some tests that result in the Spring container being dirtied
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Dirty the context after each test method.</th></tr></thead> <tbody></tbody></table></li> <li><p>Before the current test, when declared on a method with the method mode set to<code>BEFORE_METHOD</code>.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@DirtiesContext(methodMode = BEFORE_METHOD) (1)
@Test
void testProcessWhichRequiresFreshAppCtx() {
    // some logic that requires a new Spring container
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Dirty the context before the current test method.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@DirtiesContext(methodMode = BEFORE_METHOD) (1)
@Test
fun testProcessWhichRequiresFreshAppCtx() {
    // some logic that requires a new Spring container
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Dirty the context before the current test method.</th></tr></thead> <tbody></tbody></table></li> <li><p>After the current test, when declared on a method with the method mode set to<code>AFTER_METHOD</code> (i.e., the default method mode).</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@DirtiesContext (1)
@Test
void testProcessWhichDirtiesAppCtx() {
    // some logic that results in the Spring container being dirtied
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Dirty the context after the current test method.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@DirtiesContext (1)
@Test
fun testProcessWhichDirtiesAppCtx() {
    // some logic that results in the Spring container being dirtied
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Dirty the context after the current test method.</th></tr></thead> <tbody></tbody></table></li></ul> <p>If you use <code>@DirtiesContext</code> in a test whose context is configured as part of a context
hierarchy with <code>@ContextHierarchy</code>, you can use the <code>hierarchyMode</code> flag to control how
the context cache is cleared. By default, an exhaustive algorithm is used to clear the
context cache, including not only the current level but also all other context
hierarchies that share an ancestor context common to the current test. All<code>ApplicationContext</code> instances that reside in a sub-hierarchy of the common ancestor
context are removed from the context cache and closed. If the exhaustive algorithm is
overkill for a particular use case, you can specify the simpler current level algorithm,
as the following example shows.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextHierarchy({
    @ContextConfiguration(&quot;/parent-config.xml&quot;),
    @ContextConfiguration(&quot;/child-config.xml&quot;)
})
class BaseTests {
    // class body...
}

class ExtendedTests extends BaseTests {

    @Test
    @DirtiesContext(hierarchyMode = CURRENT_LEVEL) (1)
    void test() {
        // some logic that results in the child context being dirtied
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Use the current-level algorithm.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextHierarchy(
    ContextConfiguration(&quot;/parent-config.xml&quot;),
    ContextConfiguration(&quot;/child-config.xml&quot;))
open class BaseTests {
    // class body...
}

class ExtendedTests : BaseTests() {

    @Test
    @DirtiesContext(hierarchyMode = CURRENT_LEVEL) (1)
    fun test() {
        // some logic that results in the child context being dirtied
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Use the current-level algorithm.</th></tr></thead> <tbody></tbody></table> <p>For further details regarding the <code>EXHAUSTIVE</code> and <code>CURRENT_LEVEL</code> algorithms, see the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/annotation/DirtiesContext.HierarchyMode.html" target="_blank" rel="noopener noreferrer"><code>DirtiesContext.HierarchyMode</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>javadoc.</p> <h5 id="testexecutionlisteners"><a href="#testexecutionlisteners" class="header-anchor">#</a> <code>@TestExecutionListeners</code></h5> <p><code>@TestExecutionListeners</code> defines class-level metadata for configuring the<code>TestExecutionListener</code> implementations that should be registered with the<code>TestContextManager</code>. Typically, <code>@TestExecutionListeners</code> is used in conjunction with<code>@ContextConfiguration</code>.</p> <p>The following example shows how to register two <code>TestExecutionListener</code> implementations:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestExecutionListeners({CustomTestExecutionListener.class, AnotherTestExecutionListener.class}) (1)
class CustomTestExecutionListenerTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Register two <code>TestExecutionListener</code> implementations.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestExecutionListeners(CustomTestExecutionListener::class, AnotherTestExecutionListener::class) (1)
class CustomTestExecutionListenerTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Register two <code>TestExecutionListener</code> implementations.</th></tr></thead> <tbody></tbody></table> <p>By default, <code>@TestExecutionListeners</code> provides support for inheriting listeners from
superclasses or enclosing classes. See<a href="#testcontext-junit-jupiter-nested-test-configuration"><code>@Nested</code> test class configuration</a> and the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/TestExecutionListeners.html" target="_blank" rel="noopener noreferrer"><code>@TestExecutionListeners</code>javadoc<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> for an example and further details.</p> <h5 id="recordapplicationevents"><a href="#recordapplicationevents" class="header-anchor">#</a> <code>@RecordApplicationEvents</code></h5> <p><code>@RecordApplicationEvents</code> is a class-level annotation that is used to instruct the<em>Spring TestContext Framework</em> to record all application events that are published in the<code>ApplicationContext</code> during the execution of a single test.</p> <p>The recorded events can be accessed via the <code>ApplicationEvents</code> API within tests.</p> <p>See <a href="#testcontext-application-events">Application Events</a> and the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/event/RecordApplicationEvents.html" target="_blank" rel="noopener noreferrer"><code>@RecordApplicationEvents</code>javadoc<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> for an example and further details.</p> <h5 id="commit"><a href="#commit" class="header-anchor">#</a> <code>@Commit</code></h5> <p><code>@Commit</code> indicates that the transaction for a transactional test method should be
committed after the test method has completed. You can use <code>@Commit</code> as a direct
replacement for <code>@Rollback(false)</code> to more explicitly convey the intent of the code.
Analogous to <code>@Rollback</code>, <code>@Commit</code> can also be declared as a class-level or method-level
annotation.</p> <p>The following example shows how to use the <code>@Commit</code> annotation:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Commit (1)
@Test
void testProcessWithoutRollback() {
    // ...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Commit the result of the test to the database.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Commit (1)
@Test
fun testProcessWithoutRollback() {
    // ...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Commit the result of the test to the database.</th></tr></thead> <tbody></tbody></table> <h5 id="rollback"><a href="#rollback" class="header-anchor">#</a> <code>@Rollback</code></h5> <p><code>@Rollback</code> indicates whether the transaction for a transactional test method should be
rolled back after the test method has completed. If <code>true</code>, the transaction is rolled
back. Otherwise, the transaction is committed (see also<a href="#spring-testing-annotation-commit"><code>@Commit</code></a>). Rollback for integration tests in the Spring
TestContext Framework defaults to <code>true</code> even if <code>@Rollback</code> is not explicitly declared.</p> <p>When declared as a class-level annotation, <code>@Rollback</code> defines the default rollback
semantics for all test methods within the test class hierarchy. When declared as a
method-level annotation, <code>@Rollback</code> defines rollback semantics for the specific test
method, potentially overriding class-level <code>@Rollback</code> or <code>@Commit</code> semantics.</p> <p>The following example causes a test method’s result to not be rolled back (that is, the
result is committed to the database):</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Rollback(false) (1)
@Test
void testProcessWithoutRollback() {
    // ...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Do not roll back the result.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Rollback(false) (1)
@Test
fun testProcessWithoutRollback() {
    // ...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Do not roll back the result.</th></tr></thead> <tbody></tbody></table> <h5 id="beforetransaction"><a href="#beforetransaction" class="header-anchor">#</a> <code>@BeforeTransaction</code></h5> <p><code>@BeforeTransaction</code> indicates that the annotated <code>void</code> method should be run before a
transaction is started, for test methods that have been configured to run within a
transaction by using Spring’s <code>@Transactional</code> annotation. <code>@BeforeTransaction</code> methods
are not required to be <code>public</code> and may be declared on Java 8-based interface default
methods.</p> <p>The following example shows how to use the <code>@BeforeTransaction</code> annotation:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@BeforeTransaction (1)
void beforeTransaction() {
    // logic to be run before a transaction is started
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Run this method before a transaction.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@BeforeTransaction (1)
fun beforeTransaction() {
    // logic to be run before a transaction is started
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Run this method before a transaction.</th></tr></thead> <tbody></tbody></table> <h5 id="aftertransaction"><a href="#aftertransaction" class="header-anchor">#</a> <code>@AfterTransaction</code></h5> <p><code>@AfterTransaction</code> indicates that the annotated <code>void</code> method should be run after a
transaction is ended, for test methods that have been configured to run within a
transaction by using Spring’s <code>@Transactional</code> annotation. <code>@AfterTransaction</code> methods
are not required to be <code>public</code> and may be declared on Java 8-based interface default
methods.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@AfterTransaction (1)
void afterTransaction() {
    // logic to be run after a transaction has ended
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Run this method after a transaction.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@AfterTransaction (1)
fun afterTransaction() {
    // logic to be run after a transaction has ended
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Run this method after a transaction.</th></tr></thead> <tbody></tbody></table> <h5 id="sql"><a href="#sql" class="header-anchor">#</a> <code>@Sql</code></h5> <p><code>@Sql</code> is used to annotate a test class or test method to configure SQL scripts to be run
against a given database during integration tests. The following example shows how to use
it:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
@Sql({&quot;/test-schema.sql&quot;, &quot;/test-user-data.sql&quot;}) (1)
void userTest() {
    // run code that relies on the test schema and test data
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Run two scripts for this test.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
@Sql(&quot;/test-schema.sql&quot;, &quot;/test-user-data.sql&quot;) (1)
fun userTest() {
    // run code that relies on the test schema and test data
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Run two scripts for this test.</th></tr></thead> <tbody></tbody></table> <p>See <a href="#testcontext-executing-sql-declaratively">Executing SQL scripts declaratively with @Sql</a> for further details.</p> <h5 id="sqlconfig"><a href="#sqlconfig" class="header-anchor">#</a> <code>@SqlConfig</code></h5> <p><code>@SqlConfig</code> defines metadata that is used to determine how to parse and run SQL scripts
configured with the <code>@Sql</code> annotation. The following example shows how to use it:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
@Sql(
    scripts = &quot;/test-user-data.sql&quot;,
    config = @SqlConfig(commentPrefix = &quot;`&quot;, separator = &quot;@@&quot;) (1)
)
void userTest() {
    // run code that relies on the test data
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Set the comment prefix and the separator in SQL scripts.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
@Sql(&quot;/test-user-data.sql&quot;, config = SqlConfig(commentPrefix = &quot;`&quot;, separator = &quot;@@&quot;)) (1)
fun userTest() {
    // run code that relies on the test data
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Set the comment prefix and the separator in SQL scripts.</th></tr></thead> <tbody></tbody></table> <h5 id="sqlmergemode"><a href="#sqlmergemode" class="header-anchor">#</a> <code>@SqlMergeMode</code></h5> <p><code>@SqlMergeMode</code> is used to annotate a test class or test method to configure whether
method-level <code>@Sql</code> declarations are merged with class-level <code>@Sql</code> declarations. If<code>@SqlMergeMode</code> is not declared on a test class or test method, the <code>OVERRIDE</code> merge mode
will be used by default. With the <code>OVERRIDE</code> mode, method-level <code>@Sql</code> declarations will
effectively override class-level <code>@Sql</code> declarations.</p> <p>Note that a method-level <code>@SqlMergeMode</code> declaration overrides a class-level declaration.</p> <p>The following example shows how to use <code>@SqlMergeMode</code> at the class level.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig.class)
@Sql(&quot;/test-schema.sql&quot;)
@SqlMergeMode(MERGE) (1)
class UserTests {

    @Test
    @Sql(&quot;/user-test-data-001.sql&quot;)
    void standardUserProfile() {
        // run code that relies on test data set 001
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Set the <code>@Sql</code> merge mode to <code>MERGE</code> for all test methods in the class.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig::class)
@Sql(&quot;/test-schema.sql&quot;)
@SqlMergeMode(MERGE) (1)
class UserTests {

    @Test
    @Sql(&quot;/user-test-data-001.sql&quot;)
    fun standardUserProfile() {
        // run code that relies on test data set 001
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Set the <code>@Sql</code> merge mode to <code>MERGE</code> for all test methods in the class.</th></tr></thead> <tbody></tbody></table> <p>The following example shows how to use <code>@SqlMergeMode</code> at the method level.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig.class)
@Sql(&quot;/test-schema.sql&quot;)
class UserTests {

    @Test
    @Sql(&quot;/user-test-data-001.sql&quot;)
    @SqlMergeMode(MERGE) (1)
    void standardUserProfile() {
        // run code that relies on test data set 001
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Set the <code>@Sql</code> merge mode to <code>MERGE</code> for a specific test method.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig::class)
@Sql(&quot;/test-schema.sql&quot;)
class UserTests {

    @Test
    @Sql(&quot;/user-test-data-001.sql&quot;)
    @SqlMergeMode(MERGE) (1)
    fun standardUserProfile() {
        // run code that relies on test data set 001
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Set the <code>@Sql</code> merge mode to <code>MERGE</code> for a specific test method.</th></tr></thead> <tbody></tbody></table> <h5 id="sqlgroup"><a href="#sqlgroup" class="header-anchor">#</a> <code>@SqlGroup</code></h5> <p><code>@SqlGroup</code> is a container annotation that aggregates several <code>@Sql</code> annotations. You can
use <code>@SqlGroup</code> natively to declare several nested <code>@Sql</code> annotations, or you can use it
in conjunction with Java 8’s support for repeatable annotations, where <code>@Sql</code> can be
declared several times on the same class or method, implicitly generating this container
annotation. The following example shows how to declare an SQL group:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
@SqlGroup({ (1)
    @Sql(scripts = &quot;/test-schema.sql&quot;, config = @SqlConfig(commentPrefix = &quot;`&quot;)),
    @Sql(&quot;/test-user-data.sql&quot;)
)}
void userTest() {
    // run code that uses the test schema and test data
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Declare a group of SQL scripts.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
@SqlGroup( (1)
    Sql(&quot;/test-schema.sql&quot;, config = SqlConfig(commentPrefix = &quot;`&quot;)),
    Sql(&quot;/test-user-data.sql&quot;))
fun userTest() {
    // run code that uses the test schema and test data
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Declare a group of SQL scripts.</th></tr></thead> <tbody></tbody></table> <h4 id="_3-4-2-standard-annotation-support"><a href="#_3-4-2-standard-annotation-support" class="header-anchor">#</a> 3.4.2. Standard Annotation Support</h4> <p>The following annotations are supported with standard semantics for all configurations of
the Spring TestContext Framework. Note that these annotations are not specific to tests
and can be used anywhere in the Spring Framework.</p> <ul><li><p><code>@Autowired</code></p></li> <li><p><code>@Qualifier</code></p></li> <li><p><code>@Value</code></p></li> <li><p><code>@Resource</code> (javax.annotation) if JSR-250 is present</p></li> <li><p><code>@ManagedBean</code> (javax.annotation) if JSR-250 is present</p></li> <li><p><code>@Inject</code> (javax.inject) if JSR-330 is present</p></li> <li><p><code>@Named</code> (javax.inject) if JSR-330 is present</p></li> <li><p><code>@PersistenceContext</code> (javax.persistence) if JPA is present</p></li> <li><p><code>@PersistenceUnit</code> (javax.persistence) if JPA is present</p></li> <li><p><code>@Required</code></p></li> <li><p><code>@Transactional</code> (org.springframework.transaction.annotation)<em>with <a href="#testcontext-tx-attribute-support">limited attribute support</a></em></p></li></ul> <table><thead><tr><th></th> <th>JSR-250 Lifecycle Annotations<br><br>In the Spring TestContext Framework, you can use <code>@PostConstruct</code> and <code>@PreDestroy</code> with<br>standard semantics on any application components configured in the <code>ApplicationContext</code>.<br>However, these lifecycle annotations have limited usage within an actual test class.<br><br>If a method within a test class is annotated with <code>@PostConstruct</code>, that method runs<br>before any before methods of the underlying test framework (for example, methods<br>annotated with JUnit Jupiter’s <code>@BeforeEach</code>), and that applies for every test method in<br>the test class. On the other hand, if a method within a test class is annotated with<code>@PreDestroy</code>, that method never runs. Therefore, within a test class, we recommend that<br>you use test lifecycle callbacks from the underlying test framework instead of<code>@PostConstruct</code> and <code>@PreDestroy</code>.</th></tr></thead> <tbody></tbody></table> <h4 id="_3-4-3-spring-junit-4-testing-annotations"><a href="#_3-4-3-spring-junit-4-testing-annotations" class="header-anchor">#</a> 3.4.3. Spring JUnit 4 Testing Annotations</h4> <p>The following annotations are supported only when used in conjunction with the<a href="#testcontext-junit4-runner">SpringRunner</a>, <a href="#testcontext-junit4-rules">Spring’s JUnit 4
rules</a>, or <a href="#testcontext-support-classes-junit4">Spring’s JUnit 4 support classes</a>:</p> <ul><li><p><a href="#integration-testing-annotations-junit4-ifprofilevalue"><code>@IfProfileValue</code></a></p></li> <li><p><a href="#integration-testing-annotations-junit4-profilevaluesourceconfiguration"><code>@ProfileValueSourceConfiguration</code></a></p></li> <li><p><a href="#integration-testing-annotations-junit4-timed"><code>@Timed</code></a></p></li> <li><p><a href="#integration-testing-annotations-junit4-repeat"><code>@Repeat</code></a></p></li></ul> <h5 id="ifprofilevalue"><a href="#ifprofilevalue" class="header-anchor">#</a> <code>@IfProfileValue</code></h5> <p><code>@IfProfileValue</code> indicates that the annotated test is enabled for a specific testing
environment. If the configured <code>ProfileValueSource</code> returns a matching <code>value</code> for the
provided <code>name</code>, the test is enabled. Otherwise, the test is disabled and, effectively,
ignored.</p> <p>You can apply <code>@IfProfileValue</code> at the class level, the method level, or both.
Class-level usage of <code>@IfProfileValue</code> takes precedence over method-level usage for any
methods within that class or its subclasses. Specifically, a test is enabled if it is
enabled both at the class level and at the method level. The absence of <code>@IfProfileValue</code>means the test is implicitly enabled. This is analogous to the semantics of JUnit 4’s<code>@Ignore</code> annotation, except that the presence of <code>@Ignore</code> always disables a test.</p> <p>The following example shows a test that has an <code>@IfProfileValue</code> annotation:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@IfProfileValue(name=&quot;java.vendor&quot;, value=&quot;Oracle Corporation&quot;) (1)
@Test
public void testProcessWhichRunsOnlyOnOracleJvm() {
    // some logic that should run only on Java VMs from Oracle Corporation
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Run this test only when the Java vendor is &quot;Oracle Corporation&quot;.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@IfProfileValue(name=&quot;java.vendor&quot;, value=&quot;Oracle Corporation&quot;) (1)
@Test
fun testProcessWhichRunsOnlyOnOracleJvm() {
    // some logic that should run only on Java VMs from Oracle Corporation
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Run this test only when the Java vendor is &quot;Oracle Corporation&quot;.</th></tr></thead> <tbody></tbody></table> <p>Alternatively, you can configure <code>@IfProfileValue</code> with a list of <code>values</code> (with <code>OR</code>semantics) to achieve TestNG-like support for test groups in a JUnit 4 environment.
Consider the following example:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@IfProfileValue(name=&quot;test-groups&quot;, values={&quot;unit-tests&quot;, &quot;integration-tests&quot;}) (1)
@Test
public void testProcessWhichRunsForUnitOrIntegrationTestGroups() {
    // some logic that should run only for unit and integration test groups
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Run this test for unit tests and integration tests.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@IfProfileValue(name=&quot;test-groups&quot;, values=[&quot;unit-tests&quot;, &quot;integration-tests&quot;]) (1)
@Test
fun testProcessWhichRunsForUnitOrIntegrationTestGroups() {
    // some logic that should run only for unit and integration test groups
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Run this test for unit tests and integration tests.</th></tr></thead> <tbody></tbody></table> <h5 id="profilevaluesourceconfiguration"><a href="#profilevaluesourceconfiguration" class="header-anchor">#</a> <code>@ProfileValueSourceConfiguration</code></h5> <p><code>@ProfileValueSourceConfiguration</code> is a class-level annotation that specifies what type
of <code>ProfileValueSource</code> to use when retrieving profile values configured through the<code>@IfProfileValue</code> annotation. If <code>@ProfileValueSourceConfiguration</code> is not declared for a
test, <code>SystemProfileValueSource</code> is used by default. The following example shows how to
use <code>@ProfileValueSourceConfiguration</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ProfileValueSourceConfiguration(CustomProfileValueSource.class) (1)
public class CustomProfileValueSourceTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Use a custom profile value source.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ProfileValueSourceConfiguration(CustomProfileValueSource::class) (1)
class CustomProfileValueSourceTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Use a custom profile value source.</th></tr></thead> <tbody></tbody></table> <h5 id="timed"><a href="#timed" class="header-anchor">#</a> <code>@Timed</code></h5> <p><code>@Timed</code> indicates that the annotated test method must finish execution in a specified
time period (in milliseconds). If the text execution time exceeds the specified time
period, the test fails.</p> <p>The time period includes running the test method itself, any repetitions of the test (see<code>@Repeat</code>), as well as any setting up or tearing down of the test fixture. The following
example shows how to use it:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Timed(millis = 1000) (1)
public void testProcessWithOneSecondTimeout() {
    // some logic that should not take longer than 1 second to run
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Set the time period for the test to one second.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Timed(millis = 1000) (1)
fun testProcessWithOneSecondTimeout() {
    // some logic that should not take longer than 1 second to run
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Set the time period for the test to one second.</th></tr></thead> <tbody></tbody></table> <p>Spring’s <code>@Timed</code> annotation has different semantics than JUnit 4’s <code>@Test(timeout=…​)</code>support. Specifically, due to the manner in which JUnit 4 handles test execution timeouts
(that is, by executing the test method in a separate <code>Thread</code>), <code>@Test(timeout=…​)</code>preemptively fails the test if the test takes too long. Spring’s <code>@Timed</code>, on the other
hand, does not preemptively fail the test but rather waits for the test to complete
before failing.</p> <h5 id="repeat"><a href="#repeat" class="header-anchor">#</a> <code>@Repeat</code></h5> <p><code>@Repeat</code> indicates that the annotated test method must be run repeatedly. The number of
times that the test method is to be run is specified in the annotation.</p> <p>The scope of execution to be repeated includes execution of the test method itself as
well as any setting up or tearing down of the test fixture. When used with the<a href="#testcontext-junit4-rules"><code>SpringMethodRule</code></a>, the scope additionally includes
preparation of the test instance by <code>TestExecutionListener</code> implementations. The
following example shows how to use the <code>@Repeat</code> annotation:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Repeat(10) (1)
@Test
public void testProcessRepeatedly() {
    // ...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Repeat this test ten times.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Repeat(10) (1)
@Test
fun testProcessRepeatedly() {
    // ...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Repeat this test ten times.</th></tr></thead> <tbody></tbody></table> <h4 id="_3-4-4-spring-junit-jupiter-testing-annotations"><a href="#_3-4-4-spring-junit-jupiter-testing-annotations" class="header-anchor">#</a> 3.4.4. Spring JUnit Jupiter Testing Annotations</h4> <p>The following annotations are supported when used in conjunction with the<a href="#testcontext-junit-jupiter-extension"><code>SpringExtension</code></a> and JUnit Jupiter
(that is, the programming model in JUnit 5):</p> <ul><li><p><a href="#integration-testing-annotations-junit-jupiter-springjunitconfig"><code>@SpringJUnitConfig</code></a></p></li> <li><p><a href="#integration-testing-annotations-junit-jupiter-springjunitwebconfig"><code>@SpringJUnitWebConfig</code></a></p></li> <li><p><a href="#integration-testing-annotations-testconstructor"><code>@TestConstructor</code></a></p></li> <li><p><a href="#integration-testing-annotations-nestedtestconfiguration"><code>@NestedTestConfiguration</code></a></p></li> <li><p><a href="#integration-testing-annotations-junit-jupiter-enabledif"><code>@EnabledIf</code></a></p></li> <li><p><a href="#integration-testing-annotations-junit-jupiter-disabledif"><code>@DisabledIf</code></a></p></li></ul> <h5 id="springjunitconfig"><a href="#springjunitconfig" class="header-anchor">#</a> <code>@SpringJUnitConfig</code></h5> <p><code>@SpringJUnitConfig</code> is a composed annotation that combines<code>@ExtendWith(SpringExtension.class)</code> from JUnit Jupiter with <code>@ContextConfiguration</code> from
the Spring TestContext Framework. It can be used at the class level as a drop-in
replacement for <code>@ContextConfiguration</code>. With regard to configuration options, the only
difference between <code>@ContextConfiguration</code> and <code>@SpringJUnitConfig</code> is that component
classes may be declared with the <code>value</code> attribute in <code>@SpringJUnitConfig</code>.</p> <p>The following example shows how to use the <code>@SpringJUnitConfig</code> annotation to specify a
configuration class:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig.class) (1)
class ConfigurationClassJUnitJupiterSpringTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specify the configuration class.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig::class) (1)
class ConfigurationClassJUnitJupiterSpringTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specify the configuration class.</th></tr></thead> <tbody></tbody></table> <p>The following example shows how to use the <code>@SpringJUnitConfig</code> annotation to specify the
location of a configuration file:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(locations = &quot;/test-config.xml&quot;) (1)
class XmlJUnitJupiterSpringTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specify the location of a configuration file.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(locations = [&quot;/test-config.xml&quot;]) (1)
class XmlJUnitJupiterSpringTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specify the location of a configuration file.</th></tr></thead> <tbody></tbody></table> <p>See <a href="#testcontext-ctx-management">Context Management</a> as well as the javadoc for<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/junit/jupiter/SpringJUnitConfig.html" target="_blank" rel="noopener noreferrer"><code>@SpringJUnitConfig</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>and <code>@ContextConfiguration</code> for further details.</p> <h5 id="springjunitwebconfig"><a href="#springjunitwebconfig" class="header-anchor">#</a> <code>@SpringJUnitWebConfig</code></h5> <p><code>@SpringJUnitWebConfig</code> is a composed annotation that combines<code>@ExtendWith(SpringExtension.class)</code> from JUnit Jupiter with <code>@ContextConfiguration</code> and<code>@WebAppConfiguration</code> from the Spring TestContext Framework. You can use it at the class
level as a drop-in replacement for <code>@ContextConfiguration</code> and <code>@WebAppConfiguration</code>.
With regard to configuration options, the only difference between <code>@ContextConfiguration</code>and <code>@SpringJUnitWebConfig</code> is that you can declare component classes by using the<code>value</code> attribute in <code>@SpringJUnitWebConfig</code>. In addition, you can override the <code>value</code>attribute from <code>@WebAppConfiguration</code> only by using the <code>resourcePath</code> attribute in<code>@SpringJUnitWebConfig</code>.</p> <p>The following example shows how to use the <code>@SpringJUnitWebConfig</code> annotation to specify
a configuration class:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig(TestConfig.class) (1)
class ConfigurationClassJUnitJupiterSpringWebTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specify the configuration class.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig(TestConfig::class) (1)
class ConfigurationClassJUnitJupiterSpringWebTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specify the configuration class.</th></tr></thead> <tbody></tbody></table> <p>The following example shows how to use the <code>@SpringJUnitWebConfig</code> annotation to specify the
location of a configuration file:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig(locations = &quot;/test-config.xml&quot;) (1)
class XmlJUnitJupiterSpringWebTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specify the location of a configuration file.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig(locations = [&quot;/test-config.xml&quot;]) (1)
class XmlJUnitJupiterSpringWebTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specify the location of a configuration file.</th></tr></thead> <tbody></tbody></table> <p>See <a href="#testcontext-ctx-management">Context Management</a> as well as the javadoc for<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/junit/jupiter/web/SpringJUnitWebConfig.html" target="_blank" rel="noopener noreferrer"><code>@SpringJUnitWebConfig</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>,<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/ContextConfiguration.html" target="_blank" rel="noopener noreferrer"><code>@ContextConfiguration</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>, and<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/web/WebAppConfiguration.html" target="_blank" rel="noopener noreferrer"><code>@WebAppConfiguration</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>for further details.</p> <h5 id="testconstructor"><a href="#testconstructor" class="header-anchor">#</a> <code>@TestConstructor</code></h5> <p><code>@TestConstructor</code> is a type-level annotation that is used to configure how the parameters
of a test class constructor are autowired from components in the test’s<code>ApplicationContext</code>.</p> <p>If <code>@TestConstructor</code> is not present or meta-present on a test class, the default <em>test
constructor autowire mode</em> will be used. See the tip below for details on how to change
the default mode. Note, however, that a local declaration of <code>@Autowired</code> on a
constructor takes precedence over both <code>@TestConstructor</code> and the default mode.</p> <table><thead><tr><th></th> <th>Changing the default test constructor autowire mode<br><br>The default <em>test constructor autowire mode</em> can be changed by setting the<code>spring.test.constructor.autowire.mode</code> JVM system property to <code>all</code>. Alternatively, the<br>default mode may be set via the<a href="/en/spring-framework/appendix.html#appendix-spring-properties"><code>SpringProperties</code></a> mechanism.<br><br>As of Spring Framework 5.3, the default mode may also be configured as a<a href="https://junit.org/junit5/docs/current/user-guide/#running-tests-config-params" target="_blank" rel="noopener noreferrer">JUnit Platform configuration parameter<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>.<br><br>If the <code>spring.test.constructor.autowire.mode</code> property is not set, test class<br>constructors will not be automatically autowired.</th></tr></thead> <tbody></tbody></table> <table><thead><tr><th></th> <th>As of Spring Framework 5.2, <code>@TestConstructor</code> is only supported in conjunction<br>with the <code>SpringExtension</code> for use with JUnit Jupiter. Note that the <code>SpringExtension</code> is<br>often automatically registered for you – for example, when using annotations such as<code>@SpringJUnitConfig</code> and <code>@SpringJUnitWebConfig</code> or various test-related annotations from<br>Spring Boot Test.</th></tr></thead> <tbody></tbody></table> <h5 id="nestedtestconfiguration"><a href="#nestedtestconfiguration" class="header-anchor">#</a> <code>@NestedTestConfiguration</code></h5> <p><code>@NestedTestConfiguration</code> is a type-level annotation that is used to configure how
Spring test configuration annotations are processed within enclosing class hierarchies
for inner test classes.</p> <p>If <code>@NestedTestConfiguration</code> is not present or meta-present on a test class, in its
super type hierarchy, or in its enclosing class hierarchy, the default <em>enclosing
configuration inheritance mode</em> will be used. See the tip below for details on how to
change the default mode.</p> <table><thead><tr><th></th> <th>Changing the default enclosing configuration inheritance mode<br><br>The default <em>enclosing configuration inheritance mode</em> is <code>INHERIT</code>, but it can be<br>changed by setting the <code>spring.test.enclosing.configuration</code> JVM system property to<code>OVERRIDE</code>. Alternatively, the default mode may be set via the<a href="/en/spring-framework/appendix.html#appendix-spring-properties"><code>SpringProperties</code></a> mechanism.</th></tr></thead> <tbody></tbody></table> <p>The <a href="#testcontext-framework">Spring TestContext Framework</a> honors <code>@NestedTestConfiguration</code> semantics for the
following annotations.</p> <ul><li><p><a href="#spring-testing-annotation-bootstrapwith"><code>@BootstrapWith</code></a></p></li> <li><p><a href="#spring-testing-annotation-contextconfiguration"><code>@ContextConfiguration</code></a></p></li> <li><p><a href="#spring-testing-annotation-webappconfiguration"><code>@WebAppConfiguration</code></a></p></li> <li><p><a href="#spring-testing-annotation-contexthierarchy"><code>@ContextHierarchy</code></a></p></li> <li><p><a href="#spring-testing-annotation-activeprofiles"><code>@ActiveProfiles</code></a></p></li> <li><p><a href="#spring-testing-annotation-testpropertysource"><code>@TestPropertySource</code></a></p></li> <li><p><a href="#spring-testing-annotation-dynamicpropertysource"><code>@DynamicPropertySource</code></a></p></li> <li><p><a href="#spring-testing-annotation-dirtiescontext"><code>@DirtiesContext</code></a></p></li> <li><p><a href="#spring-testing-annotation-testexecutionlisteners"><code>@TestExecutionListeners</code></a></p></li> <li><p><a href="#spring-testing-annotation-recordapplicationevents"><code>@RecordApplicationEvents</code></a></p></li> <li><p><a href="#testcontext-tx"><code>@Transactional</code></a></p></li> <li><p><a href="#spring-testing-annotation-commit"><code>@Commit</code></a></p></li> <li><p><a href="#spring-testing-annotation-rollback"><code>@Rollback</code></a></p></li> <li><p><a href="#spring-testing-annotation-sql"><code>@Sql</code></a></p></li> <li><p><a href="#spring-testing-annotation-sqlconfig"><code>@SqlConfig</code></a></p></li> <li><p><a href="#spring-testing-annotation-sqlmergemode"><code>@SqlMergeMode</code></a></p></li> <li><p><a href="#integration-testing-annotations-testconstructor"><code>@TestConstructor</code></a></p></li></ul> <table><thead><tr><th></th> <th>The use of <code>@NestedTestConfiguration</code> typically only makes sense in conjunction<br>with <code>@Nested</code> test classes in JUnit Jupiter; however, there may be other testing<br>frameworks with support for Spring and nested test classes that make use of this<br>annotation.</th></tr></thead> <tbody></tbody></table> <p>See <a href="#testcontext-junit-jupiter-nested-test-configuration"><code>@Nested</code> test class configuration</a> for an example and further
details.</p> <h5 id="enabledif"><a href="#enabledif" class="header-anchor">#</a> <code>@EnabledIf</code></h5> <p><code>@EnabledIf</code> is used to signal that the annotated JUnit Jupiter test class or test method
is enabled and should be run if the supplied <code>expression</code> evaluates to <code>true</code>.
Specifically, if the expression evaluates to <code>Boolean.TRUE</code> or a <code>String</code> equal to <code>true</code>(ignoring case), the test is enabled. When applied at the class level, all test methods
within that class are automatically enabled by default as well.</p> <p>Expressions can be any of the following:</p> <ul><li><p><a href="/en/spring-framework/core.html#expressions">Spring Expression Language</a> (SpEL) expression. For example:<code>@EnabledIf(&quot;#{systemProperties['os.name'].toLowerCase().contains('mac')}&quot;)</code></p></li> <li><p>Placeholder for a property available in the Spring <a href="/en/spring-framework/core.html#beans-environment"><code>Environment</code></a>.
For example: <code>@EnabledIf(&quot;${smoke.tests.enabled}&quot;)</code></p></li> <li><p>Text literal. For example: <code>@EnabledIf(&quot;true&quot;)</code></p></li></ul> <p>Note, however, that a text literal that is not the result of dynamic resolution of a
property placeholder is of zero practical value, since <code>@EnabledIf(&quot;false&quot;)</code> is
equivalent to <code>@Disabled</code> and <code>@EnabledIf(&quot;true&quot;)</code> is logically meaningless.</p> <p>You can use <code>@EnabledIf</code> as a meta-annotation to create custom composed annotations. For
example, you can create a custom <code>@EnabledOnMac</code> annotation as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@EnabledIf(
    expression = &quot;#{systemProperties['os.name'].toLowerCase().contains('mac')}&quot;,
    reason = &quot;Enabled on Mac OS&quot;
)
public @interface EnabledOnMac {}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@EnabledIf(
        expression = &quot;#{systemProperties['os.name'].toLowerCase().contains('mac')}&quot;,
        reason = &quot;Enabled on Mac OS&quot;
)
annotation class EnabledOnMac {}
</code></pre></div><h5 id="disabledif"><a href="#disabledif" class="header-anchor">#</a> <code>@DisabledIf</code></h5> <p><code>@DisabledIf</code> is used to signal that the annotated JUnit Jupiter test class or test
method is disabled and should not be run if the supplied <code>expression</code> evaluates to<code>true</code>. Specifically, if the expression evaluates to <code>Boolean.TRUE</code> or a <code>String</code> equal
to <code>true</code> (ignoring case), the test is disabled. When applied at the class level, all
test methods within that class are automatically disabled as well.</p> <p>Expressions can be any of the following:</p> <ul><li><p><a href="/en/spring-framework/core.html#expressions">Spring Expression Language</a> (SpEL) expression. For example:<code>@DisabledIf(&quot;#{systemProperties['os.name'].toLowerCase().contains('mac')}&quot;)</code></p></li> <li><p>Placeholder for a property available in the Spring <a href="/en/spring-framework/core.html#beans-environment"><code>Environment</code></a>.
For example: <code>@DisabledIf(&quot;${smoke.tests.disabled}&quot;)</code></p></li> <li><p>Text literal. For example: <code>@DisabledIf(&quot;true&quot;)</code></p></li></ul> <p>Note, however, that a text literal that is not the result of dynamic resolution of a
property placeholder is of zero practical value, since <code>@DisabledIf(&quot;true&quot;)</code> is
equivalent to <code>@Disabled</code> and <code>@DisabledIf(&quot;false&quot;)</code> is logically meaningless.</p> <p>You can use <code>@DisabledIf</code> as a meta-annotation to create custom composed annotations. For
example, you can create a custom <code>@DisabledOnMac</code> annotation as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@DisabledIf(
    expression = &quot;#{systemProperties['os.name'].toLowerCase().contains('mac')}&quot;,
    reason = &quot;Disabled on Mac OS&quot;
)
public @interface DisabledOnMac {}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@DisabledIf(
        expression = &quot;#{systemProperties['os.name'].toLowerCase().contains('mac')}&quot;,
        reason = &quot;Disabled on Mac OS&quot;
)
annotation class DisabledOnMac {}
</code></pre></div><h4 id="_3-4-5-meta-annotation-support-for-testing"><a href="#_3-4-5-meta-annotation-support-for-testing" class="header-anchor">#</a> 3.4.5. Meta-Annotation Support for Testing</h4> <p>You can use most test-related annotations as<a href="/en/spring-framework/core.html#beans-meta-annotations">meta-annotations</a> to create custom composed
annotations and reduce configuration duplication across a test suite.</p> <p>You can use each of the following as a meta-annotation in conjunction with the<a href="#testcontext-framework">TestContext framework</a>.</p> <ul><li><p><code>@BootstrapWith</code></p></li> <li><p><code>@ContextConfiguration</code></p></li> <li><p><code>@ContextHierarchy</code></p></li> <li><p><code>@ActiveProfiles</code></p></li> <li><p><code>@TestPropertySource</code></p></li> <li><p><code>@DirtiesContext</code></p></li> <li><p><code>@WebAppConfiguration</code></p></li> <li><p><code>@TestExecutionListeners</code></p></li> <li><p><code>@Transactional</code></p></li> <li><p><code>@BeforeTransaction</code></p></li> <li><p><code>@AfterTransaction</code></p></li> <li><p><code>@Commit</code></p></li> <li><p><code>@Rollback</code></p></li> <li><p><code>@Sql</code></p></li> <li><p><code>@SqlConfig</code></p></li> <li><p><code>@SqlMergeMode</code></p></li> <li><p><code>@SqlGroup</code></p></li> <li><p><code>@Repeat</code> <em>(only supported on JUnit 4)</em></p></li> <li><p><code>@Timed</code> <em>(only supported on JUnit 4)</em></p></li> <li><p><code>@IfProfileValue</code> <em>(only supported on JUnit 4)</em></p></li> <li><p><code>@ProfileValueSourceConfiguration</code> <em>(only supported on JUnit 4)</em></p></li> <li><p><code>@SpringJUnitConfig</code> <em>(only supported on JUnit Jupiter)</em></p></li> <li><p><code>@SpringJUnitWebConfig</code> <em>(only supported on JUnit Jupiter)</em></p></li> <li><p><code>@TestConstructor</code> <em>(only supported on JUnit Jupiter)</em></p></li> <li><p><code>@NestedTestConfiguration</code> <em>(only supported on JUnit Jupiter)</em></p></li> <li><p><code>@EnabledIf</code> <em>(only supported on JUnit Jupiter)</em></p></li> <li><p><code>@DisabledIf</code> <em>(only supported on JUnit Jupiter)</em></p></li></ul> <p>Consider the following example:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@RunWith(SpringRunner.class)
@ContextConfiguration({&quot;/app-config.xml&quot;, &quot;/test-data-access-config.xml&quot;})
@ActiveProfiles(&quot;dev&quot;)
@Transactional
public class OrderRepositoryTests { }

@RunWith(SpringRunner.class)
@ContextConfiguration({&quot;/app-config.xml&quot;, &quot;/test-data-access-config.xml&quot;})
@ActiveProfiles(&quot;dev&quot;)
@Transactional
public class UserRepositoryTests { }
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@RunWith(SpringRunner::class)
@ContextConfiguration(&quot;/app-config.xml&quot;, &quot;/test-data-access-config.xml&quot;)
@ActiveProfiles(&quot;dev&quot;)
@Transactional
class OrderRepositoryTests { }

@RunWith(SpringRunner::class)
@ContextConfiguration(&quot;/app-config.xml&quot;, &quot;/test-data-access-config.xml&quot;)
@ActiveProfiles(&quot;dev&quot;)
@Transactional
class UserRepositoryTests { }
</code></pre></div><p>If we discover that we are repeating the preceding configuration across our JUnit 4-based
test suite, we can reduce the duplication by introducing a custom composed annotation
that centralizes the common test configuration for Spring, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ContextConfiguration({&quot;/app-config.xml&quot;, &quot;/test-data-access-config.xml&quot;})
@ActiveProfiles(&quot;dev&quot;)
@Transactional
public @interface TransactionalDevTestConfig { }
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Target(AnnotationTarget.TYPE)
@Retention(AnnotationRetention.RUNTIME)
@ContextConfiguration(&quot;/app-config.xml&quot;, &quot;/test-data-access-config.xml&quot;)
@ActiveProfiles(&quot;dev&quot;)
@Transactional
annotation class TransactionalDevTestConfig { }
</code></pre></div><p>Then we can use our custom <code>@TransactionalDevTestConfig</code> annotation to simplify the
configuration of individual JUnit 4 based test classes, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@RunWith(SpringRunner.class)
@TransactionalDevTestConfig
public class OrderRepositoryTests { }

@RunWith(SpringRunner.class)
@TransactionalDevTestConfig
public class UserRepositoryTests { }
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@RunWith(SpringRunner::class)
@TransactionalDevTestConfig
class OrderRepositoryTests

@RunWith(SpringRunner::class)
@TransactionalDevTestConfig
class UserRepositoryTests
</code></pre></div><p>If we write tests that use JUnit Jupiter, we can reduce code duplication even further,
since annotations in JUnit 5 can also be used as meta-annotations. Consider the following
example:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
@ContextConfiguration({&quot;/app-config.xml&quot;, &quot;/test-data-access-config.xml&quot;})
@ActiveProfiles(&quot;dev&quot;)
@Transactional
class OrderRepositoryTests { }

@ExtendWith(SpringExtension.class)
@ContextConfiguration({&quot;/app-config.xml&quot;, &quot;/test-data-access-config.xml&quot;})
@ActiveProfiles(&quot;dev&quot;)
@Transactional
class UserRepositoryTests { }
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
@ContextConfiguration(&quot;/app-config.xml&quot;, &quot;/test-data-access-config.xml&quot;)
@ActiveProfiles(&quot;dev&quot;)
@Transactional
class OrderRepositoryTests { }

@ExtendWith(SpringExtension::class)
@ContextConfiguration(&quot;/app-config.xml&quot;, &quot;/test-data-access-config.xml&quot;)
@ActiveProfiles(&quot;dev&quot;)
@Transactional
class UserRepositoryTests { }
</code></pre></div><p>If we discover that we are repeating the preceding configuration across our JUnit
Jupiter-based test suite, we can reduce the duplication by introducing a custom composed
annotation that centralizes the common test configuration for Spring and JUnit Jupiter,
as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(SpringExtension.class)
@ContextConfiguration({&quot;/app-config.xml&quot;, &quot;/test-data-access-config.xml&quot;})
@ActiveProfiles(&quot;dev&quot;)
@Transactional
public @interface TransactionalDevTestConfig { }
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Target(AnnotationTarget.TYPE)
@Retention(AnnotationRetention.RUNTIME)
@ExtendWith(SpringExtension::class)
@ContextConfiguration(&quot;/app-config.xml&quot;, &quot;/test-data-access-config.xml&quot;)
@ActiveProfiles(&quot;dev&quot;)
@Transactional
annotation class TransactionalDevTestConfig { }
</code></pre></div><p>Then we can use our custom <code>@TransactionalDevTestConfig</code> annotation to simplify the
configuration of individual JUnit Jupiter based test classes, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@TransactionalDevTestConfig
class OrderRepositoryTests { }

@TransactionalDevTestConfig
class UserRepositoryTests { }
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@TransactionalDevTestConfig
class OrderRepositoryTests { }

@TransactionalDevTestConfig
class UserRepositoryTests { }
</code></pre></div><p>Since JUnit Jupiter supports the use of <code>@Test</code>, <code>@RepeatedTest</code>, <code>ParameterizedTest</code>,
and others as meta-annotations, you can also create custom composed annotations at the
test method level. For example, if we wish to create a composed annotation that combines
the <code>@Test</code> and <code>@Tag</code> annotations from JUnit Jupiter with the <code>@Transactional</code>annotation from Spring, we could create an <code>@TransactionalIntegrationTest</code> annotation, as
follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Transactional
@Tag(&quot;integration-test&quot;) // org.junit.jupiter.api.Tag
@Test // org.junit.jupiter.api.Test
public @interface TransactionalIntegrationTest { }
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Target(AnnotationTarget.TYPE)
@Retention(AnnotationRetention.RUNTIME)
@Transactional
@Tag(&quot;integration-test&quot;) // org.junit.jupiter.api.Tag
@Test // org.junit.jupiter.api.Test
annotation class TransactionalIntegrationTest { }
</code></pre></div><p>Then we can use our custom <code>@TransactionalIntegrationTest</code> annotation to simplify the
configuration of individual JUnit Jupiter based test methods, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@TransactionalIntegrationTest
void saveOrder() { }

@TransactionalIntegrationTest
void deleteOrder() { }
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@TransactionalIntegrationTest
fun saveOrder() { }

@TransactionalIntegrationTest
fun deleteOrder() { }
</code></pre></div><p>For further details, see the<a href="https://github.com/spring-projects/spring-framework/wiki/Spring-Annotation-Programming-Model" target="_blank" rel="noopener noreferrer">Spring Annotation Programming Model<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>wiki page.</p> <h3 id="_3-5-spring-testcontext-framework"><a href="#_3-5-spring-testcontext-framework" class="header-anchor">#</a> 3.5. Spring TestContext Framework</h3> <p>The Spring TestContext Framework (located in the <code>org.springframework.test.context</code>package) provides generic, annotation-driven unit and integration testing support that is
agnostic of the testing framework in use. The TestContext framework also places a great
deal of importance on convention over configuration, with reasonable defaults that you
can override through annotation-based configuration.</p> <p>In addition to generic testing infrastructure, the TestContext framework provides
explicit support for JUnit 4, JUnit Jupiter (AKA JUnit 5), and TestNG. For JUnit 4 and
TestNG, Spring provides <code>abstract</code> support classes. Furthermore, Spring provides a custom
JUnit <code>Runner</code> and custom JUnit <code>Rules</code> for JUnit 4 and a custom <code>Extension</code> for JUnit
Jupiter that let you write so-called POJO test classes. POJO test classes are not
required to extend a particular class hierarchy, such as the <code>abstract</code> support classes.</p> <p>The following section provides an overview of the internals of the TestContext framework.
If you are interested only in using the framework and are not interested in extending it
with your own custom listeners or custom loaders, feel free to go directly to the
configuration (<a href="#testcontext-ctx-management">context management</a>,<a href="#testcontext-fixture-di">dependency injection</a>, <a href="#testcontext-tx">transaction
management</a>), <a href="#testcontext-support-classes">support classes</a>, and<a href="#integration-testing-annotations">annotation support</a> sections.</p> <h4 id="_3-5-1-key-abstractions"><a href="#_3-5-1-key-abstractions" class="header-anchor">#</a> 3.5.1. Key Abstractions</h4> <p>The core of the framework consists of the <code>TestContextManager</code> class and the<code>TestContext</code>, <code>TestExecutionListener</code>, and <code>SmartContextLoader</code> interfaces. A<code>TestContextManager</code> is created for each test class (for example, for the execution of
all test methods within a single test class in JUnit Jupiter). The <code>TestContextManager</code>,
in turn, manages a <code>TestContext</code> that holds the context of the current test. The<code>TestContextManager</code> also updates the state of the <code>TestContext</code> as the test progresses
and delegates to <code>TestExecutionListener</code> implementations, which instrument the actual
test execution by providing dependency injection, managing transactions, and so on. A<code>SmartContextLoader</code> is responsible for loading an <code>ApplicationContext</code> for a given test
class. See the <a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/package-summary.html" target="_blank" rel="noopener noreferrer">javadoc<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> and the
Spring test suite for further information and examples of various implementations.</p> <h5 id="testcontext"><a href="#testcontext" class="header-anchor">#</a> <code>TestContext</code></h5> <p><code>TestContext</code> encapsulates the context in which a test is run (agnostic of the
actual testing framework in use) and provides context management and caching support for
the test instance for which it is responsible. The <code>TestContext</code> also delegates to a<code>SmartContextLoader</code> to load an <code>ApplicationContext</code> if requested.</p> <h5 id="testcontextmanager"><a href="#testcontextmanager" class="header-anchor">#</a> <code>TestContextManager</code></h5> <p><code>TestContextManager</code> is the main entry point into the Spring TestContext Framework and is
responsible for managing a single <code>TestContext</code> and signaling events to each registered<code>TestExecutionListener</code> at well-defined test execution points:</p> <ul><li><p>Prior to any “before class” or “before all” methods of a particular testing framework.</p></li> <li><p>Test instance post-processing.</p></li> <li><p>Prior to any “before” or “before each” methods of a particular testing framework.</p></li> <li><p>Immediately before execution of the test method but after test setup.</p></li> <li><p>Immediately after execution of the test method but before test tear down.</p></li> <li><p>After any “after” or “after each” methods of a particular testing framework.</p></li> <li><p>After any “after class” or “after all” methods of a particular testing framework.</p></li></ul> <h5 id="testexecutionlistener"><a href="#testexecutionlistener" class="header-anchor">#</a> <code>TestExecutionListener</code></h5> <p><code>TestExecutionListener</code> defines the API for reacting to test-execution events published by
the <code>TestContextManager</code> with which the listener is registered. See <a href="#testcontext-tel-config"><code>TestExecutionListener</code> Configuration</a>.</p> <h5 id="context-loaders"><a href="#context-loaders" class="header-anchor">#</a> Context Loaders</h5> <p><code>ContextLoader</code> is a strategy interface for loading an <code>ApplicationContext</code> for an
integration test managed by the Spring TestContext Framework. You should implement<code>SmartContextLoader</code> instead of this interface to provide support for component classes,
active bean definition profiles, test property sources, context hierarchies, and<code>WebApplicationContext</code> support.</p> <p><code>SmartContextLoader</code> is an extension of the <code>ContextLoader</code> interface that supersedes the
original minimal <code>ContextLoader</code> SPI. Specifically, a <code>SmartContextLoader</code> can choose to
process resource locations, component classes, or context initializers. Furthermore, a<code>SmartContextLoader</code> can set active bean definition profiles and test property sources in
the context that it loads.</p> <p>Spring provides the following implementations:</p> <ul><li><p><code>DelegatingSmartContextLoader</code>: One of two default loaders, it delegates internally to
an <code>AnnotationConfigContextLoader</code>, a <code>GenericXmlContextLoader</code>, or a<code>GenericGroovyXmlContextLoader</code>, depending either on the configuration declared for the
test class or on the presence of default locations or default configuration classes.
Groovy support is enabled only if Groovy is on the classpath.</p></li> <li><p><code>WebDelegatingSmartContextLoader</code>: One of two default loaders, it delegates internally
to an <code>AnnotationConfigWebContextLoader</code>, a <code>GenericXmlWebContextLoader</code>, or a<code>GenericGroovyXmlWebContextLoader</code>, depending either on the configuration declared for
the test class or on the presence of default locations or default configuration
classes. A web <code>ContextLoader</code> is used only if <code>@WebAppConfiguration</code> is present on the
test class. Groovy support is enabled only if Groovy is on the classpath.</p></li> <li><p><code>AnnotationConfigContextLoader</code>: Loads a standard <code>ApplicationContext</code> from component
classes.</p></li> <li><p><code>AnnotationConfigWebContextLoader</code>: Loads a <code>WebApplicationContext</code> from component
classes.</p></li> <li><p><code>GenericGroovyXmlContextLoader</code>: Loads a standard <code>ApplicationContext</code> from resource
locations that are either Groovy scripts or XML configuration files.</p></li> <li><p><code>GenericGroovyXmlWebContextLoader</code>: Loads a <code>WebApplicationContext</code> from resource
locations that are either Groovy scripts or XML configuration files.</p></li> <li><p><code>GenericXmlContextLoader</code>: Loads a standard <code>ApplicationContext</code> from XML resource
locations.</p></li> <li><p><code>GenericXmlWebContextLoader</code>: Loads a <code>WebApplicationContext</code> from XML resource
locations.</p></li></ul> <h4 id="_3-5-2-bootstrapping-the-testcontext-framework"><a href="#_3-5-2-bootstrapping-the-testcontext-framework" class="header-anchor">#</a> 3.5.2. Bootstrapping the TestContext Framework</h4> <p>The default configuration for the internals of the Spring TestContext Framework is
sufficient for all common use cases. However, there are times when a development team or
third party framework would like to change the default <code>ContextLoader</code>, implement a
custom <code>TestContext</code> or <code>ContextCache</code>, augment the default sets of<code>ContextCustomizerFactory</code> and <code>TestExecutionListener</code> implementations, and so on. For
such low-level control over how the TestContext framework operates, Spring provides a
bootstrapping strategy.</p> <p><code>TestContextBootstrapper</code> defines the SPI for bootstrapping the TestContext framework. A<code>TestContextBootstrapper</code> is used by the <code>TestContextManager</code> to load the<code>TestExecutionListener</code> implementations for the current test and to build the<code>TestContext</code> that it manages. You can configure a custom bootstrapping strategy for a
test class (or test class hierarchy) by using <code>@BootstrapWith</code>, either directly or as a
meta-annotation. If a bootstrapper is not explicitly configured by using<code>@BootstrapWith</code>, either the <code>DefaultTestContextBootstrapper</code> or the<code>WebTestContextBootstrapper</code> is used, depending on the presence of <code>@WebAppConfiguration</code>.</p> <p>Since the <code>TestContextBootstrapper</code> SPI is likely to change in the future (to accommodate
new requirements), we strongly encourage implementers not to implement this interface
directly but rather to extend <code>AbstractTestContextBootstrapper</code> or one of its concrete
subclasses instead.</p> <h4 id="_3-5-3-testexecutionlistener-configuration"><a href="#_3-5-3-testexecutionlistener-configuration" class="header-anchor">#</a> 3.5.3. <code>TestExecutionListener</code> Configuration</h4> <p>Spring provides the following <code>TestExecutionListener</code> implementations that are registered
by default, exactly in the following order:</p> <ul><li><p><code>ServletTestExecutionListener</code>: Configures Servlet API mocks for a<code>WebApplicationContext</code>.</p></li> <li><p><code>DirtiesContextBeforeModesTestExecutionListener</code>: Handles the <code>@DirtiesContext</code>annotation for “before” modes.</p></li> <li><p><code>ApplicationEventsTestExecutionListener</code>: Provides support for<a href="#testcontext-application-events"><code>ApplicationEvents</code></a>.</p></li> <li><p><code>DependencyInjectionTestExecutionListener</code>: Provides dependency injection for the test
instance.</p></li> <li><p><code>DirtiesContextTestExecutionListener</code>: Handles the <code>@DirtiesContext</code> annotation for
“after” modes.</p></li> <li><p><code>TransactionalTestExecutionListener</code>: Provides transactional test execution with
default rollback semantics.</p></li> <li><p><code>SqlScriptsTestExecutionListener</code>: Runs SQL scripts configured by using the <code>@Sql</code>annotation.</p></li> <li><p><code>EventPublishingTestExecutionListener</code>: Publishes test execution events to the test’s<code>ApplicationContext</code> (see <a href="#testcontext-test-execution-events">Test Execution Events</a>).</p></li></ul> <h5 id="registering-testexecutionlistener-implementations"><a href="#registering-testexecutionlistener-implementations" class="header-anchor">#</a> Registering <code>TestExecutionListener</code> Implementations</h5> <p>You can register <code>TestExecutionListener</code> implementations for a test class and its
subclasses by using the <code>@TestExecutionListeners</code> annotation. See<a href="#integration-testing-annotations">annotation support</a> and the javadoc for<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/TestExecutionListeners.html" target="_blank" rel="noopener noreferrer"><code>@TestExecutionListeners</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>for details and examples.</p> <h5 id="automatic-discovery-of-default-testexecutionlistener-implementations"><a href="#automatic-discovery-of-default-testexecutionlistener-implementations" class="header-anchor">#</a> Automatic Discovery of Default <code>TestExecutionListener</code> Implementations</h5> <p>Registering <code>TestExecutionListener</code> implementations by using <code>@TestExecutionListeners</code> is
suitable for custom listeners that are used in limited testing scenarios. However, it can
become cumbersome if a custom listener needs to be used across an entire test suite. This
issue is addressed through support for automatic discovery of default<code>TestExecutionListener</code> implementations through the <code>SpringFactoriesLoader</code> mechanism.</p> <p>Specifically, the <code>spring-test</code> module declares all core default <code>TestExecutionListener</code>implementations under the <code>org.springframework.test.context.TestExecutionListener</code> key in
its <code>META-INF/spring.factories</code> properties file. Third-party frameworks and developers
can contribute their own <code>TestExecutionListener</code> implementations to the list of default
listeners in the same manner through their own <code>META-INF/spring.factories</code> properties
file.</p> <h5 id="ordering-testexecutionlistener-implementations"><a href="#ordering-testexecutionlistener-implementations" class="header-anchor">#</a> Ordering <code>TestExecutionListener</code> Implementations</h5> <p>When the TestContext framework discovers default <code>TestExecutionListener</code> implementations
through the <a href="#testcontext-tel-config-automatic-discovery">aforementioned</a><code>SpringFactoriesLoader</code> mechanism, the instantiated listeners are sorted by using
Spring’s <code>AnnotationAwareOrderComparator</code>, which honors Spring’s <code>Ordered</code> interface and<code>@Order</code> annotation for ordering. <code>AbstractTestExecutionListener</code> and all default<code>TestExecutionListener</code> implementations provided by Spring implement <code>Ordered</code> with
appropriate values. Third-party frameworks and developers should therefore make sure that
their default <code>TestExecutionListener</code> implementations are registered in the proper order
by implementing <code>Ordered</code> or declaring <code>@Order</code>. See the javadoc for the <code>getOrder()</code>methods of the core default <code>TestExecutionListener</code> implementations for details on what
values are assigned to each core listener.</p> <h5 id="merging-testexecutionlistener-implementations"><a href="#merging-testexecutionlistener-implementations" class="header-anchor">#</a> Merging <code>TestExecutionListener</code> Implementations</h5> <p>If a custom <code>TestExecutionListener</code> is registered via <code>@TestExecutionListeners</code>, the
default listeners are not registered. In most common testing scenarios, this effectively
forces the developer to manually declare all default listeners in addition to any custom
listeners. The following listing demonstrates this style of configuration:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestExecutionListeners({
    MyCustomTestExecutionListener.class,
    ServletTestExecutionListener.class,
    DirtiesContextBeforeModesTestExecutionListener.class,
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    SqlScriptsTestExecutionListener.class
})
class MyTest {
    // class body...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestExecutionListeners(
    MyCustomTestExecutionListener::class,
    ServletTestExecutionListener::class,
    DirtiesContextBeforeModesTestExecutionListener::class,
    DependencyInjectionTestExecutionListener::class,
    DirtiesContextTestExecutionListener::class,
    TransactionalTestExecutionListener::class,
    SqlScriptsTestExecutionListener::class
)
class MyTest {
    // class body...
}
</code></pre></div><p>The challenge with this approach is that it requires that the developer know exactly
which listeners are registered by default. Moreover, the set of default listeners can
change from release to release — for example, <code>SqlScriptsTestExecutionListener</code> was
introduced in Spring Framework 4.1, and <code>DirtiesContextBeforeModesTestExecutionListener</code>was introduced in Spring Framework 4.2. Furthermore, third-party frameworks like Spring
Boot and Spring Security register their own default <code>TestExecutionListener</code>implementations by using the aforementioned <a href="#testcontext-tel-config-automatic-discovery">automatic discovery mechanism</a>.</p> <p>To avoid having to be aware of and re-declare all default listeners, you can set the<code>mergeMode</code> attribute of <code>@TestExecutionListeners</code> to <code>MergeMode.MERGE_WITH_DEFAULTS</code>.<code>MERGE_WITH_DEFAULTS</code> indicates that locally declared listeners should be merged with the
default listeners. The merging algorithm ensures that duplicates are removed from the
list and that the resulting set of merged listeners is sorted according to the semantics
of <code>AnnotationAwareOrderComparator</code>, as described in <a href="#testcontext-tel-config-ordering">Ordering <code>TestExecutionListener</code> Implementations</a>.
If a listener implements <code>Ordered</code> or is annotated with <code>@Order</code>, it can influence the
position in which it is merged with the defaults. Otherwise, locally declared listeners
are appended to the list of default listeners when merged.</p> <p>For example, if the <code>MyCustomTestExecutionListener</code> class in the previous example
configures its <code>order</code> value (for example, <code>500</code>) to be less than the order of the<code>ServletTestExecutionListener</code> (which happens to be <code>1000</code>), the<code>MyCustomTestExecutionListener</code> can then be automatically merged with the list of
defaults in front of the <code>ServletTestExecutionListener</code>, and the previous example could
be replaced with the following:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestExecutionListeners(
    listeners = MyCustomTestExecutionListener.class,
    mergeMode = MERGE_WITH_DEFAULTS
)
class MyTest {
    // class body...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestExecutionListeners(
        listeners = [MyCustomTestExecutionListener::class],
        mergeMode = MERGE_WITH_DEFAULTS
)
class MyTest {
    // class body...
}
</code></pre></div><h4 id="_3-5-4-application-events"><a href="#_3-5-4-application-events" class="header-anchor">#</a> 3.5.4. Application Events</h4> <p>Since Spring Framework 5.3.3, the TestContext framework provides support for recording<a href="/en/spring-framework/core.html#context-functionality-events">application events</a> published in the<code>ApplicationContext</code> so that assertions can be performed against those events within
tests. All events published during the execution of a single test are made available via
the <code>ApplicationEvents</code> API which allows you to process the events as a<code>java.util.Stream</code>.</p> <p>To use <code>ApplicationEvents</code> in your tests, do the following.</p> <ul><li><p>Ensure that your test class is annotated or meta-annotated with<a href="#spring-testing-annotation-recordapplicationevents"><code>@RecordApplicationEvents</code></a>.</p></li> <li><p>Ensure that the <code>ApplicationEventsTestExecutionListener</code> is registered. Note, however,
that <code>ApplicationEventsTestExecutionListener</code> is registered by default and only needs
to be manually registered if you have custom configuration via<code>@TestExecutionListeners</code> that does not include the default listeners.</p></li> <li><p>Annotate a field of type <code>ApplicationEvents</code> with <code>@Autowired</code> and use that instance of<code>ApplicationEvents</code> in your test and lifecycle methods (such as <code>@BeforeEach</code> and<code>@AfterEach</code> methods in JUnit Jupiter).</p> <ul><li>When using the <a href="#testcontext-junit-jupiter-extension">SpringExtension for JUnit Jupiter</a>, you may declare a method
parameter of type <code>ApplicationEvents</code> in a test or lifecycle method as an alternative
to an <code>@Autowired</code> field in the test class.</li></ul></li></ul> <p>The following test class uses the <code>SpringExtension</code> for JUnit Jupiter and<a href="https://assertj.github.io/doc/" target="_blank" rel="noopener noreferrer">AssertJ<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> to assert the types of application events
published while invoking a method in a Spring-managed component:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents (1)
class OrderServiceTests {

    @Autowired
    OrderService orderService;

    @Autowired
    ApplicationEvents events; (2)

    @Test
    void submitOrder() {
        // Invoke method in OrderService that publishes an event
        orderService.submitOrder(new Order(/* ... */));
        // Verify that an OrderSubmitted event was published
        long numEvents = events.stream(OrderSubmitted.class).count(); (3)
        assertThat(numEvents).isEqualTo(1);
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Annotate the test class with <code>@RecordApplicationEvents</code>.</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Inject the <code>ApplicationEvents</code> instance for the current test.</td></tr> <tr><td><strong>3</strong></td> <td>Use the <code>ApplicationEvents</code> API to count how many <code>OrderSubmitted</code> events were published.</td></tr></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents (1)
class OrderServiceTests {

    @Autowired
    lateinit var orderService: OrderService

    @Autowired
    lateinit var events: ApplicationEvents (2)

    @Test
    fun submitOrder() {
        // Invoke method in OrderService that publishes an event
        orderService.submitOrder(Order(/* ... */))
        // Verify that an OrderSubmitted event was published
        val numEvents = events.stream(OrderSubmitted::class).count() (3)
        assertThat(numEvents).isEqualTo(1)
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Annotate the test class with <code>@RecordApplicationEvents</code>.</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Inject the <code>ApplicationEvents</code> instance for the current test.</td></tr> <tr><td><strong>3</strong></td> <td>Use the <code>ApplicationEvents</code> API to count how many <code>OrderSubmitted</code> events were published.</td></tr></tbody></table> <p>See the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/event/ApplicationEvents.html" target="_blank" rel="noopener noreferrer"><code>ApplicationEvents</code>javadoc<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> for further details regarding the <code>ApplicationEvents</code> API.</p> <h4 id="_3-5-5-test-execution-events"><a href="#_3-5-5-test-execution-events" class="header-anchor">#</a> 3.5.5. Test Execution Events</h4> <p>The <code>EventPublishingTestExecutionListener</code> introduced in Spring Framework 5.2 offers an
alternative approach to implementing a custom <code>TestExecutionListener</code>. Components in the
test’s <code>ApplicationContext</code> can listen to the following events published by the<code>EventPublishingTestExecutionListener</code>, each of which corresponds to a method in the<code>TestExecutionListener</code> API.</p> <ul><li><p><code>BeforeTestClassEvent</code></p></li> <li><p><code>PrepareTestInstanceEvent</code></p></li> <li><p><code>BeforeTestMethodEvent</code></p></li> <li><p><code>BeforeTestExecutionEvent</code></p></li> <li><p><code>AfterTestExecutionEvent</code></p></li> <li><p><code>AfterTestMethodEvent</code></p></li> <li><p><code>AfterTestClassEvent</code></p></li></ul> <table><thead><tr><th></th> <th>These events are only published if the <code>ApplicationContext</code> has already been loaded.</th></tr></thead> <tbody></tbody></table> <p>These events may be consumed for various reasons, such as resetting mock beans or tracing
test execution. One advantage of consuming test execution events rather than implementing
a custom <code>TestExecutionListener</code> is that test execution events may be consumed by any
Spring bean registered in the test <code>ApplicationContext</code>, and such beans may benefit
directly from dependency injection and other features of the <code>ApplicationContext</code>. In
contrast, a <code>TestExecutionListener</code> is not a bean in the <code>ApplicationContext</code>.</p> <p>In order to listen to test execution events, a Spring bean may choose to implement the<code>org.springframework.context.ApplicationListener</code> interface. Alternatively, listener
methods can be annotated with <code>@EventListener</code> and configured to listen to one of the
particular event types listed above (see<a href="/en/spring-framework/core.html#context-functionality-events-annotation">Annotation-based Event Listeners</a>).
Due to the popularity of this approach, Spring provides the following dedicated<code>@EventListener</code> annotations to simplify registration of test execution event listeners.
These annotations reside in the <code>org.springframework.test.context.event.annotation</code>package.</p> <ul><li><p><code>@BeforeTestClass</code></p></li> <li><p><code>@PrepareTestInstance</code></p></li> <li><p><code>@BeforeTestMethod</code></p></li> <li><p><code>@BeforeTestExecution</code></p></li> <li><p><code>@AfterTestExecution</code></p></li> <li><p><code>@AfterTestMethod</code></p></li> <li><p><code>@AfterTestClass</code></p></li></ul> <h5 id="exception-handling"><a href="#exception-handling" class="header-anchor">#</a> Exception Handling</h5> <p>By default, if a test execution event listener throws an exception while consuming an
event, that exception will propagate to the underlying testing framework in use (such as
JUnit or TestNG). For example, if the consumption of a <code>BeforeTestMethodEvent</code> results in
an exception, the corresponding test method will fail as a result of the exception. In
contrast, if an asynchronous test execution event listener throws an exception, the
exception will not propagate to the underlying testing framework. For further details on
asynchronous exception handling, consult the class-level javadoc for <code>@EventListener</code>.</p> <h5 id="asynchronous-listeners"><a href="#asynchronous-listeners" class="header-anchor">#</a> Asynchronous Listeners</h5> <p>If you want a particular test execution event listener to process events asynchronously,
you can use Spring’s <a href="/en/spring-framework/integration.html#scheduling-annotation-support-async">regular<code>@Async</code> support</a>. For further details, consult the class-level javadoc for<code>@EventListener</code>.</p> <h4 id="_3-5-6-context-management"><a href="#_3-5-6-context-management" class="header-anchor">#</a> 3.5.6. Context Management</h4> <p>Each <code>TestContext</code> provides context management and caching support for the test instance
for which it is responsible. Test instances do not automatically receive access to the
configured <code>ApplicationContext</code>. However, if a test class implements the<code>ApplicationContextAware</code> interface, a reference to the <code>ApplicationContext</code> is supplied
to the test instance. Note that <code>AbstractJUnit4SpringContextTests</code> and<code>AbstractTestNGSpringContextTests</code> implement <code>ApplicationContextAware</code> and, therefore,
provide access to the <code>ApplicationContext</code> automatically.</p> <p>|     |@Autowired ApplicationContext<br><br>As an alternative to implementing the <code>ApplicationContextAware</code> interface, you can inject<br>the application context for your test class through the <code>@Autowired</code> annotation on either<br>a field or setter method, as the following example shows:<br><br>Java<br><br><code>&lt;br/&gt;@SpringJUnitConfig&lt;br/&gt;class MyTest {&lt;br/&gt;&lt;br/&gt; @Autowired (1)&lt;br/&gt; ApplicationContext applicationContext;&lt;br/&gt;&lt;br/&gt; // class body...&lt;br/&gt;}&lt;br/&gt;</code><br><br>|<strong>1</strong>|Injecting the <code>ApplicationContext</code>.|<br>|-----|-----------------------------------|<br><br>Kotlin<br><br><code>&lt;br/&gt;@SpringJUnitConfig&lt;br/&gt;class MyTest {&lt;br/&gt;&lt;br/&gt; @Autowired (1)&lt;br/&gt; lateinit var applicationContext: ApplicationContext&lt;br/&gt;&lt;br/&gt; // class body...&lt;br/&gt;}&lt;br/&gt;</code><br><br>|<strong>1</strong>|Injecting the <code>ApplicationContext</code>.|<br>|-----|-----------------------------------|<br><br>Similarly, if your test is configured to load a <code>WebApplicationContext</code>, you can inject<br>the web application context into your test, as follows:<br><br>Java<br><br><code>&lt;br/&gt;@SpringJUnitWebConfig (1)&lt;br/&gt;class MyWebAppTest {&lt;br/&gt;&lt;br/&gt; @Autowired (2)&lt;br/&gt; WebApplicationContext wac;&lt;br/&gt;&lt;br/&gt; // class body...&lt;br/&gt;}&lt;br/&gt;</code><br><br>|<strong>1</strong>|Configuring the <code>WebApplicationContext</code>.|<br>|-----|----------------------------------------|<br>|<strong>2</strong>| Injecting the <code>WebApplicationContext</code>. |<br><br>Kotlin<br><br><code>&lt;br/&gt;@SpringJUnitWebConfig (1)&lt;br/&gt;class MyWebAppTest {&lt;br/&gt;&lt;br/&gt; @Autowired (2)&lt;br/&gt; lateinit var wac: WebApplicationContext&lt;br/&gt; // class body...&lt;br/&gt;}&lt;br/&gt;</code><br><br>|<strong>1</strong>|Configuring the <code>WebApplicationContext</code>.|<br>|-----|----------------------------------------|<br>|<strong>2</strong>| Injecting the <code>WebApplicationContext</code>. |<br><br>Dependency injection by using <code>@Autowired</code> is provided by the<code>DependencyInjectionTestExecutionListener</code>, which is configured by default<br>(see <a href="#testcontext-fixture-di">Dependency Injection of Test Fixtures</a>).|
|-----|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|<strong>1</strong>|                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Injecting the <code>ApplicationContext</code>.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
|<strong>1</strong>|                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Injecting the <code>ApplicationContext</code>.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
|<strong>1</strong>|                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     Configuring the <code>WebApplicationContext</code>.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
|<strong>2</strong>|                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Injecting the <code>WebApplicationContext</code>.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
|<strong>1</strong>|                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     Configuring the <code>WebApplicationContext</code>.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
|<strong>2</strong>|                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Injecting the <code>WebApplicationContext</code>.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |</p> <p>Test classes that use the TestContext framework do not need to extend any particular
class or implement a specific interface to configure their application context. Instead,
configuration is achieved by declaring the <code>@ContextConfiguration</code> annotation at the
class level. If your test class does not explicitly declare application context resource
locations or component classes, the configured <code>ContextLoader</code> determines how to load a
context from a default location or default configuration classes. In addition to context
resource locations and component classes, an application context can also be configured
through application context initializers.</p> <p>The following sections explain how to use Spring’s <code>@ContextConfiguration</code> annotation to
configure a test <code>ApplicationContext</code> by using XML configuration files, Groovy scripts,
component classes (typically <code>@Configuration</code> classes), or context initializers.
Alternatively, you can implement and configure your own custom <code>SmartContextLoader</code> for
advanced use cases.</p> <ul><li><p><a href="#testcontext-ctx-management-xml">Context Configuration with XML resources</a></p></li> <li><p><a href="#testcontext-ctx-management-groovy">Context Configuration with Groovy Scripts</a></p></li> <li><p><a href="#testcontext-ctx-management-javaconfig">Context Configuration with Component Classes</a></p></li> <li><p><a href="#testcontext-ctx-management-mixed-config">Mixing XML, Groovy Scripts, and Component Classes</a></p></li> <li><p><a href="#testcontext-ctx-management-initializers">Context Configuration with Context Initializers</a></p></li> <li><p><a href="#testcontext-ctx-management-inheritance">Context Configuration Inheritance</a></p></li> <li><p><a href="#testcontext-ctx-management-env-profiles">Context Configuration with Environment Profiles</a></p></li> <li><p><a href="#testcontext-ctx-management-property-sources">Context Configuration with Test Property Sources</a></p></li> <li><p><a href="#testcontext-ctx-management-dynamic-property-sources">Context Configuration with Dynamic Property Sources</a></p></li> <li><p><a href="#testcontext-ctx-management-web">Loading a <code>WebApplicationContext</code></a></p></li> <li><p><a href="#testcontext-ctx-management-caching">Context Caching</a></p></li> <li><p><a href="#testcontext-ctx-management-ctx-hierarchies">Context Hierarchies</a></p></li></ul> <h5 id="context-configuration-with-xml-resources"><a href="#context-configuration-with-xml-resources" class="header-anchor">#</a> Context Configuration with XML resources</h5> <p>To load an <code>ApplicationContext</code> for your tests by using XML configuration files, annotate
your test class with <code>@ContextConfiguration</code> and configure the <code>locations</code> attribute with
an array that contains the resource locations of XML configuration metadata. A plain or
relative path (for example, <code>context.xml</code>) is treated as a classpath resource that is
relative to the package in which the test class is defined. A path starting with a slash
is treated as an absolute classpath location (for example, <code>/org/example/config.xml</code>). A
path that represents a resource URL (i.e., a path prefixed with <code>classpath:</code>, <code>file:</code>,<code>http:</code>, etc.) is used <em>as is</em>.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from &quot;/app-config.xml&quot; and
// &quot;/test-config.xml&quot; in the root of the classpath
@ContextConfiguration(locations={&quot;/app-config.xml&quot;, &quot;/test-config.xml&quot;}) (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Setting the locations attribute to a list of XML files.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from &quot;/app-config.xml&quot; and
// &quot;/test-config.xml&quot; in the root of the classpath
@ContextConfiguration(&quot;/app-config.xml&quot;, &quot;/test-config.xml&quot;) (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Setting the locations attribute to a list of XML files.</th></tr></thead> <tbody></tbody></table> <p><code>@ContextConfiguration</code> supports an alias for the <code>locations</code> attribute through the
standard Java <code>value</code> attribute. Thus, if you do not need to declare additional
attributes in <code>@ContextConfiguration</code>, you can omit the declaration of the <code>locations</code>attribute name and declare the resource locations by using the shorthand format
demonstrated in the following example:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
@ContextConfiguration({&quot;/app-config.xml&quot;, &quot;/test-config.xml&quot;}) (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying XML files without using the <code>location</code> attribute.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
@ContextConfiguration(&quot;/app-config.xml&quot;, &quot;/test-config.xml&quot;) (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying XML files without using the <code>location</code> attribute.</th></tr></thead> <tbody></tbody></table> <p>If you omit both the <code>locations</code> and the <code>value</code> attributes from the<code>@ContextConfiguration</code> annotation, the TestContext framework tries to detect a default
XML resource location. Specifically, <code>GenericXmlContextLoader</code> and<code>GenericXmlWebContextLoader</code> detect a default location based on the name of the test
class. If your class is named <code>com.example.MyTest</code>, <code>GenericXmlContextLoader</code> loads your
application context from <code>&quot;classpath:com/example/MyTest-context.xml&quot;</code>. The following
example shows how to do so:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// &quot;classpath:com/example/MyTest-context.xml&quot;
@ContextConfiguration (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Loading configuration from the default location.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// &quot;classpath:com/example/MyTest-context.xml&quot;
@ContextConfiguration (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Loading configuration from the default location.</th></tr></thead> <tbody></tbody></table> <h5 id="context-configuration-with-groovy-scripts"><a href="#context-configuration-with-groovy-scripts" class="header-anchor">#</a> Context Configuration with Groovy Scripts</h5> <p>To load an <code>ApplicationContext</code> for your tests by using Groovy scripts that use the<a href="/en/spring-framework/core.html#groovy-bean-definition-dsl">Groovy Bean Definition DSL</a>, you can annotate
your test class with <code>@ContextConfiguration</code> and configure the <code>locations</code> or <code>value</code>attribute with an array that contains the resource locations of Groovy scripts. Resource
lookup semantics for Groovy scripts are the same as those described for<a href="#testcontext-ctx-management-xml">XML configuration files</a>.</p> <table><thead><tr><th></th> <th>Enabling Groovy script support<br><br>Support for using Groovy scripts to load an <code>ApplicationContext</code> in the Spring<br>TestContext Framework is enabled automatically if Groovy is on the classpath.</th></tr></thead> <tbody></tbody></table> <p>The following example shows how to specify Groovy configuration files:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from &quot;/AppConfig.groovy&quot; and
// &quot;/TestConfig.groovy&quot; in the root of the classpath
@ContextConfiguration({&quot;/AppConfig.groovy&quot;, &quot;/TestConfig.Groovy&quot;}) (1)
class MyTest {
    // class body...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from &quot;/AppConfig.groovy&quot; and
// &quot;/TestConfig.groovy&quot; in the root of the classpath
@ContextConfiguration(&quot;/AppConfig.groovy&quot;, &quot;/TestConfig.Groovy&quot;) (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying the location of Groovy configuration files.</th></tr></thead> <tbody></tbody></table> <p>If you omit both the <code>locations</code> and <code>value</code> attributes from the <code>@ContextConfiguration</code>annotation, the TestContext framework tries to detect a default Groovy script.
Specifically, <code>GenericGroovyXmlContextLoader</code> and <code>GenericGroovyXmlWebContextLoader</code>detect a default location based on the name of the test class. If your class is named<code>com.example.MyTest</code>, the Groovy context loader loads your application context from<code>&quot;classpath:com/example/MyTestContext.groovy&quot;</code>. The following example shows how to use
the default:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// &quot;classpath:com/example/MyTestContext.groovy&quot;
@ContextConfiguration (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Loading configuration from the default location.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// &quot;classpath:com/example/MyTestContext.groovy&quot;
@ContextConfiguration (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Loading configuration from the default location.</th></tr></thead> <tbody></tbody></table> <table><thead><tr><th></th> <th>Declaring XML configuration and Groovy scripts simultaneously<br><br>You can declare both XML configuration files and Groovy scripts simultaneously by using<br>the <code>locations</code> or <code>value</code> attribute of <code>@ContextConfiguration</code>. If the path to a<br>configured resource location ends with <code>.xml</code>, it is loaded by using an<code>XmlBeanDefinitionReader</code>. Otherwise, it is loaded by using a<code>GroovyBeanDefinitionReader</code>.<br><br>The following listing shows how to combine both in an integration test:<br><br>Java<br><br><code>&lt;br/&gt;@ExtendWith(SpringExtension.class)&lt;br/&gt;// ApplicationContext will be loaded from&lt;br/&gt;// &quot;/app-config.xml&quot; and &quot;/TestConfig.groovy&quot;&lt;br/&gt;@ContextConfiguration({ &quot;/app-config.xml&quot;, &quot;/TestConfig.groovy&quot; })&lt;br/&gt;class MyTest {&lt;br/&gt; // class body...&lt;br/&gt;}&lt;br/&gt;</code><br><br>Kotlin<br><br><code>&lt;br/&gt;@ExtendWith(SpringExtension::class)&lt;br/&gt;// ApplicationContext will be loaded from&lt;br/&gt;// &quot;/app-config.xml&quot; and &quot;/TestConfig.groovy&quot;&lt;br/&gt;@ContextConfiguration(&quot;/app-config.xml&quot;, &quot;/TestConfig.groovy&quot;)&lt;br/&gt;class MyTest {&lt;br/&gt; // class body...&lt;br/&gt;}&lt;br/&gt;</code></th></tr></thead> <tbody></tbody></table> <h5 id="context-configuration-with-component-classes"><a href="#context-configuration-with-component-classes" class="header-anchor">#</a> Context Configuration with Component Classes</h5> <p>To load an <code>ApplicationContext</code> for your tests by using component classes (see<a href="/en/spring-framework/core.html#beans-java">Java-based container configuration</a>), you can annotate your test
class with <code>@ContextConfiguration</code> and configure the <code>classes</code> attribute with an array
that contains references to component classes. The following example shows how to do so:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes = {AppConfig.class, TestConfig.class}) (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying component classes.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes = [AppConfig::class, TestConfig::class]) (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying component classes.</th></tr></thead> <tbody></tbody></table> <table><thead><tr><th></th> <th>Component Classes<br><br>The term “component class” can refer to any of the following:<br><br>* A class annotated with <code>@Configuration</code>.<br><br>* A component (that is, a class annotated with <code>@Component</code>, <code>@Service</code>, <code>@Repository</code>, or other stereotype annotations).<br><br>* A JSR-330 compliant class that is annotated with <code>javax.inject</code> annotations.<br><br>* Any class that contains <code>@Bean</code>-methods.<br><br>* Any other class that is intended to be registered as a Spring component (i.e., a Spring<br>  bean in the <code>ApplicationContext</code>), potentially taking advantage of automatic autowiring<br>  of a single constructor without the use of Spring annotations.<br><br>See the javadoc of<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/Configuration.html" target="_blank" rel="noopener noreferrer"><code>@Configuration</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> and<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/Bean.html" target="_blank" rel="noopener noreferrer"><code>@Bean</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> for further information<br>regarding the configuration and semantics of component classes, paying special attention<br>to the discussion of <code>@Bean</code> Lite Mode.</th></tr></thead> <tbody></tbody></table> <p>If you omit the <code>classes</code> attribute from the <code>@ContextConfiguration</code> annotation, the
TestContext framework tries to detect the presence of default configuration classes.
Specifically, <code>AnnotationConfigContextLoader</code> and <code>AnnotationConfigWebContextLoader</code>detect all <code>static</code> nested classes of the test class that meet the requirements for
configuration class implementations, as specified in the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/Configuration.html" target="_blank" rel="noopener noreferrer"><code>@Configuration</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> javadoc.
Note that the name of the configuration class is arbitrary. In addition, a test class can
contain more than one <code>static</code> nested configuration class if desired. In the following
example, the <code>OrderServiceTest</code> class declares a <code>static</code> nested configuration class
named <code>Config</code> that is automatically used to load the <code>ApplicationContext</code> for the test
class:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig (1)
// ApplicationContext will be loaded from the
// static nested Config class
class OrderServiceTest {

    @Configuration
    static class Config {

        // this bean will be injected into the OrderServiceTest class
        @Bean
        OrderService orderService() {
            OrderService orderService = new OrderServiceImpl();
            // set properties, etc.
            return orderService;
        }
    }

    @Autowired
    OrderService orderService;

    @Test
    void testOrderService() {
        // test the orderService
    }

}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Loading configuration information from the nested <code>Config</code> class.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig (1)
// ApplicationContext will be loaded from the nested Config class
class OrderServiceTest {

    @Autowired
    lateinit var orderService: OrderService

    @Configuration
    class Config {

        // this bean will be injected into the OrderServiceTest class
        @Bean
        fun orderService(): OrderService {
            // set properties, etc.
            return OrderServiceImpl()
        }
    }

    @Test
    fun testOrderService() {
        // test the orderService
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Loading configuration information from the nested <code>Config</code> class.</th></tr></thead> <tbody></tbody></table> <h5 id="mixing-xml-groovy-scripts-and-component-classes"><a href="#mixing-xml-groovy-scripts-and-component-classes" class="header-anchor">#</a> Mixing XML, Groovy Scripts, and Component Classes</h5> <p>It may sometimes be desirable to mix XML configuration files, Groovy scripts, and
component classes (typically <code>@Configuration</code> classes) to configure an<code>ApplicationContext</code> for your tests. For example, if you use XML configuration in
production, you may decide that you want to use <code>@Configuration</code> classes to configure
specific Spring-managed components for your tests, or vice versa.</p> <p>Furthermore, some third-party frameworks (such as Spring Boot) provide first-class
support for loading an <code>ApplicationContext</code> from different types of resources
simultaneously (for example, XML configuration files, Groovy scripts, and<code>@Configuration</code> classes). The Spring Framework, historically, has not supported this for
standard deployments. Consequently, most of the <code>SmartContextLoader</code> implementations that
the Spring Framework delivers in the <code>spring-test</code> module support only one resource type
for each test context. However, this does not mean that you cannot use both. One
exception to the general rule is that the <code>GenericGroovyXmlContextLoader</code> and<code>GenericGroovyXmlWebContextLoader</code> support both XML configuration files and Groovy
scripts simultaneously. Furthermore, third-party frameworks may choose to support the
declaration of both <code>locations</code> and <code>classes</code> through <code>@ContextConfiguration</code>, and, with
the standard testing support in the TestContext framework, you have the following options.</p> <p>If you want to use resource locations (for example, XML or Groovy) and <code>@Configuration</code>classes to configure your tests, you must pick one as the entry point, and that one must
include or import the other. For example, in XML or Groovy scripts, you can include<code>@Configuration</code> classes by using component scanning or defining them as normal Spring
beans, whereas, in a <code>@Configuration</code> class, you can use <code>@ImportResource</code> to import XML
configuration files or Groovy scripts. Note that this behavior is semantically equivalent
to how you configure your application in production: In production configuration, you
define either a set of XML or Groovy resource locations or a set of <code>@Configuration</code>classes from which your production <code>ApplicationContext</code> is loaded, but you still have the
freedom to include or import the other type of configuration.</p> <h5 id="context-configuration-with-context-initializers"><a href="#context-configuration-with-context-initializers" class="header-anchor">#</a> Context Configuration with Context Initializers</h5> <p>To configure an <code>ApplicationContext</code> for your tests by using context initializers,
annotate your test class with <code>@ContextConfiguration</code> and configure the <code>initializers</code>attribute with an array that contains references to classes that implement<code>ApplicationContextInitializer</code>. The declared context initializers are then used to
initialize the <code>ConfigurableApplicationContext</code> that is loaded for your tests. Note that
the concrete <code>ConfigurableApplicationContext</code> type supported by each declared initializer
must be compatible with the type of <code>ApplicationContext</code> created by the<code>SmartContextLoader</code> in use (typically a <code>GenericApplicationContext</code>). Furthermore, the
order in which the initializers are invoked depends on whether they implement Spring’s<code>Ordered</code> interface or are annotated with Spring’s <code>@Order</code> annotation or the standard<code>@Priority</code> annotation. The following example shows how to use initializers:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from TestConfig
// and initialized by TestAppCtxInitializer
@ContextConfiguration(
    classes = TestConfig.class,
    initializers = TestAppCtxInitializer.class) (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying configuration by using a configuration class and an initializer.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from TestConfig
// and initialized by TestAppCtxInitializer
@ContextConfiguration(
        classes = [TestConfig::class],
        initializers = [TestAppCtxInitializer::class]) (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying configuration by using a configuration class and an initializer.</th></tr></thead> <tbody></tbody></table> <p>You can also omit the declaration of XML configuration files, Groovy scripts, or
component classes in <code>@ContextConfiguration</code> entirely and instead declare only<code>ApplicationContextInitializer</code> classes, which are then responsible for registering beans
in the context — for example, by programmatically loading bean definitions from XML
files or configuration classes. The following example shows how to do so:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
// ApplicationContext will be initialized by EntireAppInitializer
// which presumably registers beans in the context
@ContextConfiguration(initializers = EntireAppInitializer.class) (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying configuration by using only an initializer.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
// ApplicationContext will be initialized by EntireAppInitializer
// which presumably registers beans in the context
@ContextConfiguration(initializers = [EntireAppInitializer::class]) (1)
class MyTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying configuration by using only an initializer.</th></tr></thead> <tbody></tbody></table> <h5 id="context-configuration-inheritance"><a href="#context-configuration-inheritance" class="header-anchor">#</a> Context Configuration Inheritance</h5> <p><code>@ContextConfiguration</code> supports boolean <code>inheritLocations</code> and <code>inheritInitializers</code>attributes that denote whether resource locations or component classes and context
initializers declared by superclasses should be inherited. The default value for both
flags is <code>true</code>. This means that a test class inherits the resource locations or
component classes as well as the context initializers declared by any superclasses.
Specifically, the resource locations or component classes for a test class are appended
to the list of resource locations or annotated classes declared by superclasses.
Similarly, the initializers for a given test class are added to the set of initializers
defined by test superclasses. Thus, subclasses have the option of extending the resource
locations, component classes, or context initializers.</p> <p>If the <code>inheritLocations</code> or <code>inheritInitializers</code> attribute in <code>@ContextConfiguration</code>is set to <code>false</code>, the resource locations or component classes and the context
initializers, respectively, for the test class shadow and effectively replace the
configuration defined by superclasses.</p> <table><thead><tr><th></th> <th>As of Spring Framework 5.3, test configuration may also be inherited from enclosing<br>classes. See <a href="#testcontext-junit-jupiter-nested-test-configuration"><code>@Nested</code> test class configuration</a> for details.</th></tr></thead> <tbody></tbody></table> <p>In the next example, which uses XML resource locations, the <code>ApplicationContext</code> for<code>ExtendedTest</code> is loaded from <code>base-config.xml</code> and <code>extended-config.xml</code>, in that order.
Beans defined in <code>extended-config.xml</code> can, therefore, override (that is, replace) those
defined in <code>base-config.xml</code>. The following example shows how one class can extend
another and use both its own configuration file and the superclass’s configuration file:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from &quot;/base-config.xml&quot;
// in the root of the classpath
@ContextConfiguration(&quot;/base-config.xml&quot;) (1)
class BaseTest {
    // class body...
}

// ApplicationContext will be loaded from &quot;/base-config.xml&quot; and
// &quot;/extended-config.xml&quot; in the root of the classpath
@ContextConfiguration(&quot;/extended-config.xml&quot;) (2)
class ExtendedTest extends BaseTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Configuration file defined in the superclass.</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Configuration file defined in the subclass.</td></tr></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from &quot;/base-config.xml&quot;
// in the root of the classpath
@ContextConfiguration(&quot;/base-config.xml&quot;) (1)
open class BaseTest {
    // class body...
}

// ApplicationContext will be loaded from &quot;/base-config.xml&quot; and
// &quot;/extended-config.xml&quot; in the root of the classpath
@ContextConfiguration(&quot;/extended-config.xml&quot;) (2)
class ExtendedTest : BaseTest() {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Configuration file defined in the superclass.</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Configuration file defined in the subclass.</td></tr></tbody></table> <p>Similarly, in the next example, which uses component classes, the <code>ApplicationContext</code>for <code>ExtendedTest</code> is loaded from the <code>BaseConfig</code> and <code>ExtendedConfig</code> classes, in that
order. Beans defined in <code>ExtendedConfig</code> can, therefore, override (that is, replace)
those defined in <code>BaseConfig</code>. The following example shows how one class can extend
another and use both its own configuration class and the superclass’s configuration class:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// ApplicationContext will be loaded from BaseConfig
@SpringJUnitConfig(BaseConfig.class) (1)
class BaseTest {
    // class body...
}

// ApplicationContext will be loaded from BaseConfig and ExtendedConfig
@SpringJUnitConfig(ExtendedConfig.class) (2)
class ExtendedTest extends BaseTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Configuration class defined in the superclass.</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Configuration class defined in the subclass.</td></tr></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// ApplicationContext will be loaded from BaseConfig
@SpringJUnitConfig(BaseConfig::class) (1)
open class BaseTest {
    // class body...
}

// ApplicationContext will be loaded from BaseConfig and ExtendedConfig
@SpringJUnitConfig(ExtendedConfig::class) (2)
class ExtendedTest : BaseTest() {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Configuration class defined in the superclass.</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Configuration class defined in the subclass.</td></tr></tbody></table> <p>In the next example, which uses context initializers, the <code>ApplicationContext</code> for<code>ExtendedTest</code> is initialized by using <code>BaseInitializer</code> and <code>ExtendedInitializer</code>. Note,
however, that the order in which the initializers are invoked depends on whether they
implement Spring’s <code>Ordered</code> interface or are annotated with Spring’s <code>@Order</code> annotation
or the standard <code>@Priority</code> annotation. The following example shows how one class can
extend another and use both its own initializer and the superclass’s initializer:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// ApplicationContext will be initialized by BaseInitializer
@SpringJUnitConfig(initializers = BaseInitializer.class) (1)
class BaseTest {
    // class body...
}

// ApplicationContext will be initialized by BaseInitializer
// and ExtendedInitializer
@SpringJUnitConfig(initializers = ExtendedInitializer.class) (2)
class ExtendedTest extends BaseTest {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Initializer defined in the superclass.</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Initializer defined in the subclass.</td></tr></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// ApplicationContext will be initialized by BaseInitializer
@SpringJUnitConfig(initializers = [BaseInitializer::class]) (1)
open class BaseTest {
    // class body...
}

// ApplicationContext will be initialized by BaseInitializer
// and ExtendedInitializer
@SpringJUnitConfig(initializers = [ExtendedInitializer::class]) (2)
class ExtendedTest : BaseTest() {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Initializer defined in the superclass.</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Initializer defined in the subclass.</td></tr></tbody></table> <h5 id="context-configuration-with-environment-profiles"><a href="#context-configuration-with-environment-profiles" class="header-anchor">#</a> Context Configuration with Environment Profiles</h5> <p>The Spring Framework has first-class support for the notion of environments and profiles
(AKA &quot;bean definition profiles&quot;), and integration tests can be configured to activate
particular bean definition profiles for various testing scenarios. This is achieved by
annotating a test class with the <code>@ActiveProfiles</code> annotation and supplying a list of
profiles that should be activated when loading the <code>ApplicationContext</code> for the test.</p> <table><thead><tr><th></th> <th>You can use <code>@ActiveProfiles</code> with any implementation of the <code>SmartContextLoader</code>SPI, but <code>@ActiveProfiles</code> is not supported with implementations of the older<code>ContextLoader</code> SPI.</th></tr></thead> <tbody></tbody></table> <p>Consider two examples with XML configuration and <code>@Configuration</code> classes:</p> <div class="language- extra-class"><pre class="language-text"><code>&lt;!-- app-config.xml --&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xmlns:jdbc=&quot;http://www.springframework.org/schema/jdbc&quot;
    xmlns:jee=&quot;http://www.springframework.org/schema/jee&quot;
    xsi:schemaLocation=&quot;...&quot;&gt;

    &lt;bean id=&quot;transferService&quot;
            class=&quot;com.bank.service.internal.DefaultTransferService&quot;&gt;
        &lt;constructor-arg ref=&quot;accountRepository&quot;/&gt;
        &lt;constructor-arg ref=&quot;feePolicy&quot;/&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;accountRepository&quot;
            class=&quot;com.bank.repository.internal.JdbcAccountRepository&quot;&gt;
        &lt;constructor-arg ref=&quot;dataSource&quot;/&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;feePolicy&quot;
        class=&quot;com.bank.service.internal.ZeroFeePolicy&quot;/&gt;

    &lt;beans profile=&quot;dev&quot;&gt;
        &lt;jdbc:embedded-database id=&quot;dataSource&quot;&gt;
            &lt;jdbc:script
                location=&quot;classpath:com/bank/config/sql/schema.sql&quot;/&gt;
            &lt;jdbc:script
                location=&quot;classpath:com/bank/config/sql/test-data.sql&quot;/&gt;
        &lt;/jdbc:embedded-database&gt;
    &lt;/beans&gt;

    &lt;beans profile=&quot;production&quot;&gt;
        &lt;jee:jndi-lookup id=&quot;dataSource&quot; jndi-name=&quot;java:comp/env/jdbc/datasource&quot;/&gt;
    &lt;/beans&gt;

    &lt;beans profile=&quot;default&quot;&gt;
        &lt;jdbc:embedded-database id=&quot;dataSource&quot;&gt;
            &lt;jdbc:script
                location=&quot;classpath:com/bank/config/sql/schema.sql&quot;/&gt;
        &lt;/jdbc:embedded-database&gt;
    &lt;/beans&gt;

&lt;/beans&gt;
</code></pre></div><p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from &quot;classpath:/app-config.xml&quot;
@ContextConfiguration(&quot;/app-config.xml&quot;)
@ActiveProfiles(&quot;dev&quot;)
class TransferServiceTest {

    @Autowired
    TransferService transferService;

    @Test
    void testTransferService() {
        // test the transferService
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from &quot;classpath:/app-config.xml&quot;
@ContextConfiguration(&quot;/app-config.xml&quot;)
@ActiveProfiles(&quot;dev&quot;)
class TransferServiceTest {

    @Autowired
    lateinit var transferService: TransferService

    @Test
    fun testTransferService() {
        // test the transferService
    }
}
</code></pre></div><p>When <code>TransferServiceTest</code> is run, its <code>ApplicationContext</code> is loaded from the<code>app-config.xml</code> configuration file in the root of the classpath. If you inspect<code>app-config.xml</code>, you can see that the <code>accountRepository</code> bean has a dependency on a<code>dataSource</code> bean. However, <code>dataSource</code> is not defined as a top-level bean. Instead,<code>dataSource</code> is defined three times: in the <code>production</code> profile, in the <code>dev</code> profile,
and in the <code>default</code> profile.</p> <p>By annotating <code>TransferServiceTest</code> with <code>@ActiveProfiles(&quot;dev&quot;)</code>, we instruct the Spring
TestContext Framework to load the <code>ApplicationContext</code> with the active profiles set to<code>{&quot;dev&quot;}</code>. As a result, an embedded database is created and populated with test data, and
the <code>accountRepository</code> bean is wired with a reference to the development <code>DataSource</code>.
That is likely what we want in an integration test.</p> <p>It is sometimes useful to assign beans to a <code>default</code> profile. Beans within the default
profile are included only when no other profile is specifically activated. You can use
this to define “fallback” beans to be used in the application’s default state. For
example, you may explicitly provide a data source for <code>dev</code> and <code>production</code> profiles,
but define an in-memory data source as a default when neither of these is active.</p> <p>The following code listings demonstrate how to implement the same configuration and
integration test with <code>@Configuration</code> classes instead of XML:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Configuration
@Profile(&quot;dev&quot;)
public class StandaloneDataConfig {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript(&quot;classpath:com/bank/config/sql/schema.sql&quot;)
            .addScript(&quot;classpath:com/bank/config/sql/test-data.sql&quot;)
            .build();
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Configuration
@Profile(&quot;dev&quot;)
class StandaloneDataConfig {

    @Bean
    fun dataSource(): DataSource {
        return EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.HSQL)
                .addScript(&quot;classpath:com/bank/config/sql/schema.sql&quot;)
                .addScript(&quot;classpath:com/bank/config/sql/test-data.sql&quot;)
                .build()
    }
}
</code></pre></div><p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Configuration
@Profile(&quot;production&quot;)
public class JndiDataConfig {

    @Bean(destroyMethod=&quot;&quot;)
    public DataSource dataSource() throws Exception {
        Context ctx = new InitialContext();
        return (DataSource) ctx.lookup(&quot;java:comp/env/jdbc/datasource&quot;);
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Configuration
@Profile(&quot;production&quot;)
class JndiDataConfig {

    @Bean(destroyMethod = &quot;&quot;)
    fun dataSource(): DataSource {
        val ctx = InitialContext()
        return ctx.lookup(&quot;java:comp/env/jdbc/datasource&quot;) as DataSource
    }
}
</code></pre></div><p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Configuration
@Profile(&quot;default&quot;)
public class DefaultDataConfig {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript(&quot;classpath:com/bank/config/sql/schema.sql&quot;)
            .build();
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Configuration
@Profile(&quot;default&quot;)
class DefaultDataConfig {

    @Bean
    fun dataSource(): DataSource {
        return EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.HSQL)
                .addScript(&quot;classpath:com/bank/config/sql/schema.sql&quot;)
                .build()
    }
}
</code></pre></div><p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Configuration
public class TransferServiceConfig {

    @Autowired DataSource dataSource;

    @Bean
    public TransferService transferService() {
        return new DefaultTransferService(accountRepository(), feePolicy());
    }

    @Bean
    public AccountRepository accountRepository() {
        return new JdbcAccountRepository(dataSource);
    }

    @Bean
    public FeePolicy feePolicy() {
        return new ZeroFeePolicy();
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Configuration
class TransferServiceConfig {

    @Autowired
    lateinit var dataSource: DataSource

    @Bean
    fun transferService(): TransferService {
        return DefaultTransferService(accountRepository(), feePolicy())
    }

    @Bean
    fun accountRepository(): AccountRepository {
        return JdbcAccountRepository(dataSource)
    }

    @Bean
    fun feePolicy(): FeePolicy {
        return ZeroFeePolicy()
    }
}
</code></pre></div><p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig({
        TransferServiceConfig.class,
        StandaloneDataConfig.class,
        JndiDataConfig.class,
        DefaultDataConfig.class})
@ActiveProfiles(&quot;dev&quot;)
class TransferServiceTest {

    @Autowired
    TransferService transferService;

    @Test
    void testTransferService() {
        // test the transferService
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(
        TransferServiceConfig::class,
        StandaloneDataConfig::class,
        JndiDataConfig::class,
        DefaultDataConfig::class)
@ActiveProfiles(&quot;dev&quot;)
class TransferServiceTest {

    @Autowired
    lateinit var transferService: TransferService

    @Test
    fun testTransferService() {
        // test the transferService
    }
}
</code></pre></div><p>In this variation, we have split the XML configuration into four independent<code>@Configuration</code> classes:</p> <ul><li><p><code>TransferServiceConfig</code>: Acquires a <code>dataSource</code> through dependency injection by using<code>@Autowired</code>.</p></li> <li><p><code>StandaloneDataConfig</code>: Defines a <code>dataSource</code> for an embedded database suitable for
developer tests.</p></li> <li><p><code>JndiDataConfig</code>: Defines a <code>dataSource</code> that is retrieved from JNDI in a production
environment.</p></li> <li><p><code>DefaultDataConfig</code>: Defines a <code>dataSource</code> for a default embedded database, in case no
profile is active.</p></li></ul> <p>As with the XML-based configuration example, we still annotate <code>TransferServiceTest</code> with<code>@ActiveProfiles(&quot;dev&quot;)</code>, but this time we specify all four configuration classes by
using the <code>@ContextConfiguration</code> annotation. The body of the test class itself remains
completely unchanged.</p> <p>It is often the case that a single set of profiles is used across multiple test classes
within a given project. Thus, to avoid duplicate declarations of the <code>@ActiveProfiles</code>annotation, you can declare <code>@ActiveProfiles</code> once on a base class, and subclasses
automatically inherit the <code>@ActiveProfiles</code> configuration from the base class. In the
following example, the declaration of <code>@ActiveProfiles</code> (as well as other annotations)
has been moved to an abstract superclass, <code>AbstractIntegrationTest</code>:</p> <table><thead><tr><th></th> <th>As of Spring Framework 5.3, test configuration may also be inherited from enclosing<br>classes. See <a href="#testcontext-junit-jupiter-nested-test-configuration"><code>@Nested</code> test class configuration</a> for details.</th></tr></thead> <tbody></tbody></table> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig({
        TransferServiceConfig.class,
        StandaloneDataConfig.class,
        JndiDataConfig.class,
        DefaultDataConfig.class})
@ActiveProfiles(&quot;dev&quot;)
abstract class AbstractIntegrationTest {
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(
        TransferServiceConfig::class,
        StandaloneDataConfig::class,
        JndiDataConfig::class,
        DefaultDataConfig::class)
@ActiveProfiles(&quot;dev&quot;)
abstract class AbstractIntegrationTest {
}
</code></pre></div><p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// &quot;dev&quot; profile inherited from superclass
class TransferServiceTest extends AbstractIntegrationTest {

    @Autowired
    TransferService transferService;

    @Test
    void testTransferService() {
        // test the transferService
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// &quot;dev&quot; profile inherited from superclass
class TransferServiceTest : AbstractIntegrationTest() {

    @Autowired
    lateinit var transferService: TransferService

    @Test
    fun testTransferService() {
        // test the transferService
    }
}
</code></pre></div><p><code>@ActiveProfiles</code> also supports an <code>inheritProfiles</code> attribute that can be used to
disable the inheritance of active profiles, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// &quot;dev&quot; profile overridden with &quot;production&quot;
@ActiveProfiles(profiles = &quot;production&quot;, inheritProfiles = false)
class ProductionTransferServiceTest extends AbstractIntegrationTest {
    // test body
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// &quot;dev&quot; profile overridden with &quot;production&quot;
@ActiveProfiles(&quot;production&quot;, inheritProfiles = false)
class ProductionTransferServiceTest : AbstractIntegrationTest() {
    // test body
}
</code></pre></div><p>Furthermore, it is sometimes necessary to resolve active profiles for tests
programmatically instead of declaratively — for example, based on:</p> <ul><li><p>The current operating system.</p></li> <li><p>Whether tests are being run on a continuous integration build server.</p></li> <li><p>The presence of certain environment variables.</p></li> <li><p>The presence of custom class-level annotations.</p></li> <li><p>Other concerns.</p></li></ul> <p>To resolve active bean definition profiles programmatically, you can implement
a custom <code>ActiveProfilesResolver</code> and register it by using the <code>resolver</code>attribute of <code>@ActiveProfiles</code>. For further information, see the corresponding<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/ActiveProfilesResolver.html" target="_blank" rel="noopener noreferrer">javadoc<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>.
The following example demonstrates how to implement and register a custom<code>OperatingSystemActiveProfilesResolver</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// &quot;dev&quot; profile overridden programmatically via a custom resolver
@ActiveProfiles(
        resolver = OperatingSystemActiveProfilesResolver.class,
        inheritProfiles = false)
class TransferServiceTest extends AbstractIntegrationTest {
    // test body
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// &quot;dev&quot; profile overridden programmatically via a custom resolver
@ActiveProfiles(
        resolver = OperatingSystemActiveProfilesResolver::class,
        inheritProfiles = false)
class TransferServiceTest : AbstractIntegrationTest() {
    // test body
}
</code></pre></div><p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>public class OperatingSystemActiveProfilesResolver implements ActiveProfilesResolver {

    @Override
    public String[] resolve(Class&lt;?&gt; testClass) {
        String profile = ...;
        // determine the value of profile based on the operating system
        return new String[] {profile};
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>class OperatingSystemActiveProfilesResolver : ActiveProfilesResolver {

    override fun resolve(testClass: Class&lt;*&gt;): Array&lt;String&gt; {
        val profile: String = ...
        // determine the value of profile based on the operating system
        return arrayOf(profile)
    }
}
</code></pre></div><h5 id="context-configuration-with-test-property-sources"><a href="#context-configuration-with-test-property-sources" class="header-anchor">#</a> Context Configuration with Test Property Sources</h5> <p>The Spring Framework has first-class support for the notion of an environment with a
hierarchy of property sources, and you can configure integration tests with test-specific
property sources. In contrast to the <code>@PropertySource</code> annotation used on<code>@Configuration</code> classes, you can declare the <code>@TestPropertySource</code> annotation on a test
class to declare resource locations for test properties files or inlined properties.
These test property sources are added to the set of <code>PropertySources</code> in the<code>Environment</code> for the <code>ApplicationContext</code> loaded for the annotated integration test.</p> <table><thead><tr><th></th> <th>You can use <code>@TestPropertySource</code> with any implementation of the <code>SmartContextLoader</code>SPI, but <code>@TestPropertySource</code> is not supported with implementations of the older<code>ContextLoader</code> SPI.<br><br>Implementations of <code>SmartContextLoader</code> gain access to merged test property source values<br>through the <code>getPropertySourceLocations()</code> and <code>getPropertySourceProperties()</code> methods in<code>MergedContextConfiguration</code>.</th></tr></thead> <tbody></tbody></table> <h6 id="declaring-test-property-sources"><a href="#declaring-test-property-sources" class="header-anchor">#</a> Declaring Test Property Sources</h6> <p>You can configure test properties files by using the <code>locations</code> or <code>value</code> attribute of<code>@TestPropertySource</code>.</p> <p>Both traditional and XML-based properties file formats are supported — for example,<code>&quot;classpath:/com/example/test.properties&quot;</code> or <code>&quot;file:///path/to/file.xml&quot;</code>.</p> <p>Each path is interpreted as a Spring <code>Resource</code>. A plain path (for example,<code>&quot;test.properties&quot;</code>) is treated as a classpath resource that is relative to the package
in which the test class is defined. A path starting with a slash is treated as an
absolute classpath resource (for example: <code>&quot;/org/example/test.xml&quot;</code>). A path that
references a URL (for example, a path prefixed with <code>classpath:</code>, <code>file:</code>, or <code>http:</code>) is
loaded by using the specified resource protocol. Resource location wildcards (such as<code>***/**.properties</code>) are not permitted: Each location must evaluate to exactly one<code>.properties</code> or <code>.xml</code> resource.</p> <p>The following example uses a test properties file:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestPropertySource(&quot;/test.properties&quot;) (1)
class MyIntegrationTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying a properties file with an absolute path.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestPropertySource(&quot;/test.properties&quot;) (1)
class MyIntegrationTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specifying a properties file with an absolute path.</th></tr></thead> <tbody></tbody></table> <p>You can configure inlined properties in the form of key-value pairs by using the<code>properties</code> attribute of <code>@TestPropertySource</code>, as shown in the next example. All
key-value pairs are added to the enclosing <code>Environment</code> as a single test<code>PropertySource</code> with the highest precedence.</p> <p>The supported syntax for key-value pairs is the same as the syntax defined for entries in
a Java properties file:</p> <ul><li><p><code>key=value</code></p></li> <li><p><code>key:value</code></p></li> <li><p><code>key value</code></p></li></ul> <p>The following example sets two inlined properties:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestPropertySource(properties = {&quot;timezone = GMT&quot;, &quot;port: 4242&quot;}) (1)
class MyIntegrationTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Setting two properties by using two variations of the key-value syntax.</th></tr></thead> <tbody></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestPropertySource(properties = [&quot;timezone = GMT&quot;, &quot;port: 4242&quot;]) (1)
class MyIntegrationTests {
    // class body...
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Setting two properties by using two variations of the key-value syntax.</th></tr></thead> <tbody></tbody></table> <table><thead><tr><th></th> <th>As of Spring Framework 5.2, <code>@TestPropertySource</code> can be used as <em>repeatable annotation</em>.<br>That means that you can have multiple declarations of <code>@TestPropertySource</code> on a single<br>test class, with the <code>locations</code> and <code>properties</code> from later <code>@TestPropertySource</code>annotations overriding those from previous <code>@TestPropertySource</code> annotations.<br><br>In addition, you may declare multiple composed annotations on a test class that are each<br>meta-annotated with <code>@TestPropertySource</code>, and all of those <code>@TestPropertySource</code>declarations will contribute to your test property sources.<br><br>Directly present <code>@TestPropertySource</code> annotations always take precedence over<br>meta-present <code>@TestPropertySource</code> annotations. In other words, <code>locations</code> and<code>properties</code> from a directly present <code>@TestPropertySource</code> annotation will override the<code>locations</code> and <code>properties</code> from a <code>@TestPropertySource</code> annotation used as a<br>meta-annotation.</th></tr></thead> <tbody></tbody></table> <h6 id="default-properties-file-detection"><a href="#default-properties-file-detection" class="header-anchor">#</a> Default Properties File Detection</h6> <p>If <code>@TestPropertySource</code> is declared as an empty annotation (that is, without explicit
values for the <code>locations</code> or <code>properties</code> attributes), an attempt is made to detect a
default properties file relative to the class that declared the annotation. For example,
if the annotated test class is <code>com.example.MyTest</code>, the corresponding default properties
file is <code>classpath:com/example/MyTest.properties</code>. If the default cannot be detected, an<code>IllegalStateException</code> is thrown.</p> <h6 id="precedence"><a href="#precedence" class="header-anchor">#</a> Precedence</h6> <p>Test properties have higher precedence than those defined in the operating system’s
environment, Java system properties, or property sources added by the application
declaratively by using <code>@PropertySource</code> or programmatically. Thus, test properties can
be used to selectively override properties loaded from system and application property
sources. Furthermore, inlined properties have higher precedence than properties loaded
from resource locations. Note, however, that properties registered via<a href="#testcontext-ctx-management-dynamic-property-sources"><code>@DynamicPropertySource</code></a> have
higher precedence than those loaded via <code>@TestPropertySource</code>.</p> <p>In the next example, the <code>timezone</code> and <code>port</code> properties and any properties defined in<code>&quot;/test.properties&quot;</code> override any properties of the same name that are defined in system
and application property sources. Furthermore, if the <code>&quot;/test.properties&quot;</code> file defines
entries for the <code>timezone</code> and <code>port</code> properties those are overridden by the inlined
properties declared by using the <code>properties</code> attribute. The following example shows how
to specify properties both in a file and inline:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestPropertySource(
    locations = &quot;/test.properties&quot;,
    properties = {&quot;timezone = GMT&quot;, &quot;port: 4242&quot;}
)
class MyIntegrationTests {
    // class body...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration
@TestPropertySource(&quot;/test.properties&quot;,
        properties = [&quot;timezone = GMT&quot;, &quot;port: 4242&quot;]
)
class MyIntegrationTests {
    // class body...
}
</code></pre></div><h6 id="inheriting-and-overriding-test-property-sources"><a href="#inheriting-and-overriding-test-property-sources" class="header-anchor">#</a> Inheriting and Overriding Test Property Sources</h6> <p><code>@TestPropertySource</code> supports boolean <code>inheritLocations</code> and <code>inheritProperties</code>attributes that denote whether resource locations for properties files and inlined
properties declared by superclasses should be inherited. The default value for both flags
is <code>true</code>. This means that a test class inherits the locations and inlined properties
declared by any superclasses. Specifically, the locations and inlined properties for a
test class are appended to the locations and inlined properties declared by superclasses.
Thus, subclasses have the option of extending the locations and inlined properties. Note
that properties that appear later shadow (that is, override) properties of the same name
that appear earlier. In addition, the aforementioned precedence rules apply for inherited
test property sources as well.</p> <p>If the <code>inheritLocations</code> or <code>inheritProperties</code> attribute in <code>@TestPropertySource</code> is
set to <code>false</code>, the locations or inlined properties, respectively, for the test class
shadow and effectively replace the configuration defined by superclasses.</p> <table><thead><tr><th></th> <th>As of Spring Framework 5.3, test configuration may also be inherited from enclosing<br>classes. See <a href="#testcontext-junit-jupiter-nested-test-configuration"><code>@Nested</code> test class configuration</a> for details.</th></tr></thead> <tbody></tbody></table> <p>In the next example, the <code>ApplicationContext</code> for <code>BaseTest</code> is loaded by using only the<code>base.properties</code> file as a test property source. In contrast, the <code>ApplicationContext</code>for <code>ExtendedTest</code> is loaded by using the <code>base.properties</code> and <code>extended.properties</code>files as test property source locations. The following example shows how to define
properties in both a subclass and its superclass by using <code>properties</code> files:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@TestPropertySource(&quot;base.properties&quot;)
@ContextConfiguration
class BaseTest {
    // ...
}

@TestPropertySource(&quot;extended.properties&quot;)
@ContextConfiguration
class ExtendedTest extends BaseTest {
    // ...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@TestPropertySource(&quot;base.properties&quot;)
@ContextConfiguration
open class BaseTest {
    // ...
}

@TestPropertySource(&quot;extended.properties&quot;)
@ContextConfiguration
class ExtendedTest : BaseTest() {
    // ...
}
</code></pre></div><p>In the next example, the <code>ApplicationContext</code> for <code>BaseTest</code> is loaded by using only the
inlined <code>key1</code> property. In contrast, the <code>ApplicationContext</code> for <code>ExtendedTest</code> is
loaded by using the inlined <code>key1</code> and <code>key2</code> properties. The following example shows how
to define properties in both a subclass and its superclass by using inline properties:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@TestPropertySource(properties = &quot;key1 = value1&quot;)
@ContextConfiguration
class BaseTest {
    // ...
}

@TestPropertySource(properties = &quot;key2 = value2&quot;)
@ContextConfiguration
class ExtendedTest extends BaseTest {
    // ...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@TestPropertySource(properties = [&quot;key1 = value1&quot;])
@ContextConfiguration
open class BaseTest {
    // ...
}

@TestPropertySource(properties = [&quot;key2 = value2&quot;])
@ContextConfiguration
class ExtendedTest : BaseTest() {
    // ...
}
</code></pre></div><h5 id="context-configuration-with-dynamic-property-sources"><a href="#context-configuration-with-dynamic-property-sources" class="header-anchor">#</a> Context Configuration with Dynamic Property Sources</h5> <p>As of Spring Framework 5.2.5, the TestContext framework provides support for <em>dynamic</em>properties via the <code>@DynamicPropertySource</code> annotation. This annotation can be used in
integration tests that need to add properties with dynamic values to the set of<code>PropertySources</code> in the <code>Environment</code> for the <code>ApplicationContext</code> loaded for the
integration test.</p> <table><thead><tr><th></th> <th>The <code>@DynamicPropertySource</code> annotation and its supporting infrastructure were<br>originally designed to allow properties from<a href="https://www.testcontainers.org/" target="_blank" rel="noopener noreferrer">Testcontainers<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> based tests to be exposed easily to<br>Spring integration tests. However, this feature may also be used with any form of<br>external resource whose lifecycle is maintained outside the test’s <code>ApplicationContext</code>.</th></tr></thead> <tbody></tbody></table> <p>In contrast to the <a href="#testcontext-ctx-management-property-sources"><code>@TestPropertySource</code></a>annotation that is applied at the class level, <code>@DynamicPropertySource</code> must be applied
to a <code>static</code> method that accepts a single <code>DynamicPropertyRegistry</code> argument which is
used to add <em>name-value</em> pairs to the <code>Environment</code>. Values are dynamic and provided via
a <code>Supplier</code> which is only invoked when the property is resolved. Typically, method
references are used to supply values, as can be seen in the following example which uses
the Testcontainers project to manage a Redis container outside of the Spring<code>ApplicationContext</code>. The IP address and port of the managed Redis container are made
available to components within the test’s <code>ApplicationContext</code> via the <code>redis.host</code> and<code>redis.port</code> properties. These properties can be accessed via Spring’s <code>Environment</code>abstraction or injected directly into Spring-managed components – for example, via<code>@Value(&quot;${redis.host}&quot;)</code> and <code>@Value(&quot;${redis.port}&quot;)</code>, respectively.</p> <table><thead><tr><th></th> <th>If you use <code>@DynamicPropertySource</code> in a base class and discover that tests in subclasses<br>fail because the dynamic properties change between subclasses, you may need to annotate<br>your base class with <a href="#spring-testing-annotation-dirtiescontext"><code>@DirtiesContext</code></a> to<br>ensure that each subclass gets its own <code>ApplicationContext</code> with the correct dynamic<br>properties.</th></tr></thead> <tbody></tbody></table> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(/* ... */)
@Testcontainers
class ExampleIntegrationTests {

    @Container
    static RedisContainer redis = new RedisContainer();

    @DynamicPropertySource
    static void redisProperties(DynamicPropertyRegistry registry) {
        registry.add(&quot;redis.host&quot;, redis::getContainerIpAddress);
        registry.add(&quot;redis.port&quot;, redis::getMappedPort);
    }

    // tests ...

}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(/* ... */)
@Testcontainers
class ExampleIntegrationTests {

    companion object {

        @Container
        @JvmStatic
        val redis: RedisContainer = RedisContainer()

        @DynamicPropertySource
        @JvmStatic
        fun redisProperties(registry: DynamicPropertyRegistry) {
            registry.add(&quot;redis.host&quot;, redis::getContainerIpAddress)
            registry.add(&quot;redis.port&quot;, redis::getMappedPort)
        }
    }

    // tests ...

}
</code></pre></div><h6 id="precedence-2"><a href="#precedence-2" class="header-anchor">#</a> Precedence</h6> <p>Dynamic properties have higher precedence than those loaded from <code>@TestPropertySource</code>,
the operating system’s environment, Java system properties, or property sources added by
the application declaratively by using <code>@PropertySource</code> or programmatically. Thus,
dynamic properties can be used to selectively override properties loaded via<code>@TestPropertySource</code>, system property sources, and application property sources.</p> <h5 id="loading-a-webapplicationcontext"><a href="#loading-a-webapplicationcontext" class="header-anchor">#</a> Loading a <code>WebApplicationContext</code></h5> <p>To instruct the TestContext framework to load a <code>WebApplicationContext</code> instead of a
standard <code>ApplicationContext</code>, you can annotate the respective test class with<code>@WebAppConfiguration</code>.</p> <p>The presence of <code>@WebAppConfiguration</code> on your test class instructs the TestContext
framework (TCF) that a <code>WebApplicationContext</code> (WAC) should be loaded for your
integration tests. In the background, the TCF makes sure that a <code>MockServletContext</code> is
created and supplied to your test’s WAC. By default, the base resource path for your<code>MockServletContext</code> is set to <code>src/main/webapp</code>. This is interpreted as a path relative
to the root of your JVM (normally the path to your project). If you are familiar with the
directory structure of a web application in a Maven project, you know that<code>src/main/webapp</code> is the default location for the root of your WAR. If you need to
override this default, you can provide an alternate path to the <code>@WebAppConfiguration</code>annotation (for example, <code>@WebAppConfiguration(&quot;src/test/webapp&quot;)</code>). If you wish to
reference a base resource path from the classpath instead of the file system, you can use
Spring’s <code>classpath:</code> prefix.</p> <p>Note that Spring’s testing support for <code>WebApplicationContext</code> implementations is on par
with its support for standard <code>ApplicationContext</code> implementations. When testing with a<code>WebApplicationContext</code>, you are free to declare XML configuration files, Groovy scripts,
or <code>@Configuration</code> classes by using <code>@ContextConfiguration</code>. You are also free to use
any other test annotations, such as <code>@ActiveProfiles</code>, <code>@TestExecutionListeners</code>, <code>@Sql</code>,<code>@Rollback</code>, and others.</p> <p>The remaining examples in this section show some of the various configuration options for
loading a <code>WebApplicationContext</code>. The following example shows the TestContext
framework’s support for convention over configuration:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)

// defaults to &quot;file:src/main/webapp&quot;
@WebAppConfiguration

// detects &quot;WacTests-context.xml&quot; in the same package
// or static nested @Configuration classes
@ContextConfiguration
class WacTests {
    //...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)

// defaults to &quot;file:src/main/webapp&quot;
@WebAppConfiguration

// detects &quot;WacTests-context.xml&quot; in the same package
// or static nested @Configuration classes
@ContextConfiguration
class WacTests {
    //...
}
</code></pre></div><p>If you annotate a test class with <code>@WebAppConfiguration</code> without specifying a resource
base path, the resource path effectively defaults to <code>file:src/main/webapp</code>. Similarly,
if you declare <code>@ContextConfiguration</code> without specifying resource <code>locations</code>, component<code>classes</code>, or context <code>initializers</code>, Spring tries to detect the presence of your
configuration by using conventions (that is, <code>WacTests-context.xml</code> in the same package
as the <code>WacTests</code> class or static nested <code>@Configuration</code> classes).</p> <p>The following example shows how to explicitly declare a resource base path with<code>@WebAppConfiguration</code> and an XML resource location with <code>@ContextConfiguration</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)

// file system resource
@WebAppConfiguration(&quot;webapp&quot;)

// classpath resource
@ContextConfiguration(&quot;/spring/test-servlet-config.xml&quot;)
class WacTests {
    //...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)

// file system resource
@WebAppConfiguration(&quot;webapp&quot;)

// classpath resource
@ContextConfiguration(&quot;/spring/test-servlet-config.xml&quot;)
class WacTests {
    //...
}
</code></pre></div><p>The important thing to note here is the different semantics for paths with these two
annotations. By default, <code>@WebAppConfiguration</code> resource paths are file system based,
whereas <code>@ContextConfiguration</code> resource locations are classpath based.</p> <p>The following example shows that we can override the default resource semantics for both
annotations by specifying a Spring resource prefix:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)

// classpath resource
@WebAppConfiguration(&quot;classpath:test-web-resources&quot;)

// file system resource
@ContextConfiguration(&quot;file:src/main/webapp/WEB-INF/servlet-config.xml&quot;)
class WacTests {
    //...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)

// classpath resource
@WebAppConfiguration(&quot;classpath:test-web-resources&quot;)

// file system resource
@ContextConfiguration(&quot;file:src/main/webapp/WEB-INF/servlet-config.xml&quot;)
class WacTests {
    //...
}
</code></pre></div><p>Contrast the comments in this example with the previous example.</p> <p><a href=""></a>Working with Web Mocks</p> <p>To provide comprehensive web testing support, the TestContext framework has a<code>ServletTestExecutionListener</code> that is enabled by default. When testing against a<code>WebApplicationContext</code>, this <a href="#testcontext-key-abstractions"><code>TestExecutionListener</code></a>sets up default thread-local state by using Spring Web’s <code>RequestContextHolder</code> before
each test method and creates a <code>MockHttpServletRequest</code>, a <code>MockHttpServletResponse</code>, and
a <code>ServletWebRequest</code> based on the base resource path configured with<code>@WebAppConfiguration</code>. <code>ServletTestExecutionListener</code> also ensures that the<code>MockHttpServletResponse</code> and <code>ServletWebRequest</code> can be injected into the test instance,
and, once the test is complete, it cleans up thread-local state.</p> <p>Once you have a <code>WebApplicationContext</code> loaded for your test, you might find that you
need to interact with the web mocks — for example, to set up your test fixture or to
perform assertions after invoking your web component. The following example shows which
mocks can be autowired into your test instance. Note that the <code>WebApplicationContext</code> and<code>MockServletContext</code> are both cached across the test suite, whereas the other mocks are
managed per test method by the <code>ServletTestExecutionListener</code>.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig
class WacTests {

    @Autowired
    WebApplicationContext wac; // cached

    @Autowired
    MockServletContext servletContext; // cached

    @Autowired
    MockHttpSession session;

    @Autowired
    MockHttpServletRequest request;

    @Autowired
    MockHttpServletResponse response;

    @Autowired
    ServletWebRequest webRequest;

    //...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig
class WacTests {

    @Autowired
    lateinit var wac: WebApplicationContext // cached

    @Autowired
    lateinit var servletContext: MockServletContext // cached

    @Autowired
    lateinit var session: MockHttpSession

    @Autowired
    lateinit var request: MockHttpServletRequest

    @Autowired
    lateinit var response: MockHttpServletResponse

    @Autowired
    lateinit var webRequest: ServletWebRequest

    //...
}
</code></pre></div><h5 id="context-caching"><a href="#context-caching" class="header-anchor">#</a> Context Caching</h5> <p>Once the TestContext framework loads an <code>ApplicationContext</code> (or <code>WebApplicationContext</code>)
for a test, that context is cached and reused for all subsequent tests that declare the
same unique context configuration within the same test suite. To understand how caching
works, it is important to understand what is meant by “unique” and “test suite.”</p> <p>An <code>ApplicationContext</code> can be uniquely identified by the combination of configuration
parameters that is used to load it. Consequently, the unique combination of configuration
parameters is used to generate a key under which the context is cached. The TestContext
framework uses the following configuration parameters to build the context cache key:</p> <ul><li><p><code>locations</code> (from <code>@ContextConfiguration</code>)</p></li> <li><p><code>classes</code> (from <code>@ContextConfiguration</code>)</p></li> <li><p><code>contextInitializerClasses</code> (from <code>@ContextConfiguration</code>)</p></li> <li><p><code>contextCustomizers</code> (from <code>ContextCustomizerFactory</code>) – this includes<code>@DynamicPropertySource</code> methods as well as various features from Spring Boot’s
testing support such as <code>@MockBean</code> and <code>@SpyBean</code>.</p></li> <li><p><code>contextLoader</code> (from <code>@ContextConfiguration</code>)</p></li> <li><p><code>parent</code> (from <code>@ContextHierarchy</code>)</p></li> <li><p><code>activeProfiles</code> (from <code>@ActiveProfiles</code>)</p></li> <li><p><code>propertySourceLocations</code> (from <code>@TestPropertySource</code>)</p></li> <li><p><code>propertySourceProperties</code> (from <code>@TestPropertySource</code>)</p></li> <li><p><code>resourceBasePath</code> (from <code>@WebAppConfiguration</code>)</p></li></ul> <p>For example, if <code>TestClassA</code> specifies <code>{&quot;app-config.xml&quot;, &quot;test-config.xml&quot;}</code> for the<code>locations</code> (or <code>value</code>) attribute of <code>@ContextConfiguration</code>, the TestContext framework
loads the corresponding <code>ApplicationContext</code> and stores it in a <code>static</code> context cache
under a key that is based solely on those locations. So, if <code>TestClassB</code> also defines<code>{&quot;app-config.xml&quot;, &quot;test-config.xml&quot;}</code> for its locations (either explicitly or
implicitly through inheritance) but does not define <code>@WebAppConfiguration</code>, a different<code>ContextLoader</code>, different active profiles, different context initializers, different
test property sources, or a different parent context, then the same <code>ApplicationContext</code>is shared by both test classes. This means that the setup cost for loading an application
context is incurred only once (per test suite), and subsequent test execution is much
faster.</p> <table><thead><tr><th></th> <th>Test suites and forked processes<br><br>The Spring TestContext framework stores application contexts in a static cache. This<br>means that the context is literally stored in a <code>static</code> variable. In other words, if<br>tests run in separate processes, the static cache is cleared between each test<br>execution, which effectively disables the caching mechanism.<br><br>To benefit from the caching mechanism, all tests must run within the same process or test<br>suite. This can be achieved by executing all tests as a group within an IDE. Similarly,<br>when executing tests with a build framework such as Ant, Maven, or Gradle, it is<br>important to make sure that the build framework does not fork between tests. For example,<br>if the<a href="https://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html#forkMode" target="_blank" rel="noopener noreferrer"><code>forkMode</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>for the Maven Surefire plug-in is set to <code>always</code> or <code>pertest</code>, the TestContext framework<br>cannot cache application contexts between test classes, and the build process runs<br>significantly more slowly as a result.</th></tr></thead> <tbody></tbody></table> <p>The size of the context cache is bounded with a default maximum size of 32. Whenever the
maximum size is reached, a least recently used (LRU) eviction policy is used to evict and
close stale contexts. You can configure the maximum size from the command line or a build
script by setting a JVM system property named <code>spring.test.context.cache.maxSize</code>. As an
alternative, you can set the same property via the<a href="/en/spring-framework/appendix.html#appendix-spring-properties"><code>SpringProperties</code></a> mechanism.</p> <p>Since having a large number of application contexts loaded within a given test suite can
cause the suite to take an unnecessarily long time to run, it is often beneficial to
know exactly how many contexts have been loaded and cached. To view the statistics for
the underlying context cache, you can set the log level for the<code>org.springframework.test.context.cache</code> logging category to <code>DEBUG</code>.</p> <p>In the unlikely case that a test corrupts the application context and requires reloading
(for example, by modifying a bean definition or the state of an application object), you
can annotate your test class or test method with <code>@DirtiesContext</code> (see the discussion of<code>@DirtiesContext</code> in <a href="#spring-testing-annotation-dirtiescontext">Spring Testing
Annotations</a>). This instructs Spring to remove the context from the cache and rebuild
the application context before running the next test that requires the same application
context. Note that support for the <code>@DirtiesContext</code> annotation is provided by the<code>DirtiesContextBeforeModesTestExecutionListener</code> and the<code>DirtiesContextTestExecutionListener</code>, which are enabled by default.</p> <table><thead><tr><th></th> <th>ApplicationContext lifecycle and console logging<br><br>When you need to debug a test executed with the Spring TestContext Framework, it can be<br>useful to analyze the console output (that is, output to the <code>SYSOUT</code> and <code>SYSERR</code>streams). Some build tools and IDEs are able to associate console output with a given<br>test; however, some console output cannot be easily associated with a given test.<br><br>With regard to console logging triggered by the Spring Framework itself or by components<br>registered in the <code>ApplicationContext</code>, it is important to understand the lifecycle of an<code>ApplicationContext</code> that has been loaded by the Spring TestContext Framework within a<br>test suite.<br><br>The <code>ApplicationContext</code> for a test is typically loaded when an instance of the test<br>class is being prepared — for example, to perform dependency injection into <code>@Autowired</code>fields of the test instance. This means that any console logging triggered during the<br>initialization of the <code>ApplicationContext</code> typically cannot be associated with an<br>individual test method. However, if the context is closed immediately before the<br>execution of a test method according to <a href="#spring-testing-annotation-dirtiescontext"><code>@DirtiesContext</code></a>semantics, a new instance of the context will be loaded just prior to execution of the<br>test method. In the latter scenario, an IDE or build tool may potentially associate<br>console logging with the individual test method.<br><br>The <code>ApplicationContext</code> for a test can be closed via one of the following scenarios.<br><br>* The context is closed according to <code>@DirtiesContext</code> semantics.<br><br>* The context is closed because it has been automatically evicted from the cache<br>  according to the LRU eviction policy.<br><br>* The context is closed via a JVM shutdown hook when the JVM for the test suite<br>  terminates.<br><br>If the context is closed according to <code>@DirtiesContext</code> semantics after a particular test<br>method, an IDE or build tool may potentially associate console logging with the<br>individual test method. If the context is closed according to <code>@DirtiesContext</code> semantics<br>after a test class, any console logging triggered during the shutdown of the<code>ApplicationContext</code> cannot be associated with an individual test method. Similarly, any<br>console logging triggered during the shutdown phase via a JVM shutdown hook cannot be<br>associated with an individual test method.<br><br>When a Spring <code>ApplicationContext</code> is closed via a JVM shutdown hook, callbacks executed<br>during the shutdown phase are executed on a thread named <code>SpringContextShutdownHook</code>. So,<br>if you wish to disable console logging triggered when the <code>ApplicationContext</code> is closed<br>via a JVM shutdown hook, you may be able to register a custom filter with your logging<br>framework that allows you to ignore any logging initiated by that thread.</th></tr></thead> <tbody></tbody></table> <h5 id="context-hierarchies"><a href="#context-hierarchies" class="header-anchor">#</a> Context Hierarchies</h5> <p>When writing integration tests that rely on a loaded Spring <code>ApplicationContext</code>, it is
often sufficient to test against a single context. However, there are times when it is
beneficial or even necessary to test against a hierarchy of <code>ApplicationContext</code>instances. For example, if you are developing a Spring MVC web application, you typically
have a root <code>WebApplicationContext</code> loaded by Spring’s <code>ContextLoaderListener</code> and a
child <code>WebApplicationContext</code> loaded by Spring’s <code>DispatcherServlet</code>. This results in a
parent-child context hierarchy where shared components and infrastructure configuration
are declared in the root context and consumed in the child context by web-specific
components. Another use case can be found in Spring Batch applications, where you often
have a parent context that provides configuration for shared batch infrastructure and a
child context for the configuration of a specific batch job.</p> <p>You can write integration tests that use context hierarchies by declaring context
configuration with the <code>@ContextHierarchy</code> annotation, either on an individual test class
or within a test class hierarchy. If a context hierarchy is declared on multiple classes
within a test class hierarchy, you can also merge or override the context configuration
for a specific, named level in the context hierarchy. When merging configuration for a
given level in the hierarchy, the configuration resource type (that is, XML configuration
files or component classes) must be consistent. Otherwise, it is perfectly acceptable to
have different levels in a context hierarchy configured using different resource types.</p> <p>The remaining JUnit Jupiter based examples in this section show common configuration
scenarios for integration tests that require the use of context hierarchies.</p> <p>Single test class with context hierarchy</p> <p><code>ControllerIntegrationTests</code> represents a typical integration testing scenario for a
Spring MVC web application by declaring a context hierarchy that consists of two levels,
one for the root <code>WebApplicationContext</code> (loaded by using the <code>TestAppConfig``@Configuration</code> class) and one for the dispatcher servlet <code>WebApplicationContext</code>(loaded by using the <code>WebConfig</code> <code>@Configuration</code> class). The <code>WebApplicationContext</code>that is autowired into the test instance is the one for the child context (that is, the
lowest context in the hierarchy). The following listing shows this configuration scenario:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextHierarchy({
    @ContextConfiguration(classes = TestAppConfig.class),
    @ContextConfiguration(classes = WebConfig.class)
})
class ControllerIntegrationTests {

    @Autowired
    WebApplicationContext wac;

    // ...
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
@WebAppConfiguration
@ContextHierarchy(
    ContextConfiguration(classes = [TestAppConfig::class]),
    ContextConfiguration(classes = [WebConfig::class]))
class ControllerIntegrationTests {

    @Autowired
    lateinit var wac: WebApplicationContext

    // ...
}
</code></pre></div><p>Class hierarchy with implicit parent context</p> <p>The test classes in this example define a context hierarchy within a test class
hierarchy. <code>AbstractWebTests</code> declares the configuration for a root<code>WebApplicationContext</code> in a Spring-powered web application. Note, however, that<code>AbstractWebTests</code> does not declare <code>@ContextHierarchy</code>. Consequently, subclasses of<code>AbstractWebTests</code> can optionally participate in a context hierarchy or follow the
standard semantics for <code>@ContextConfiguration</code>. <code>SoapWebServiceTests</code> and<code>RestWebServiceTests</code> both extend <code>AbstractWebTests</code> and define a context hierarchy by
using <code>@ContextHierarchy</code>. The result is that three application contexts are loaded (one
for each declaration of <code>@ContextConfiguration</code>), and the application context loaded
based on the configuration in <code>AbstractWebTests</code> is set as the parent context for each of
the contexts loaded for the concrete subclasses. The following listing shows this
configuration scenario:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextConfiguration(&quot;file:src/main/webapp/WEB-INF/applicationContext.xml&quot;)
public abstract class AbstractWebTests {}

@ContextHierarchy(@ContextConfiguration(&quot;/spring/soap-ws-config.xml&quot;))
public class SoapWebServiceTests extends AbstractWebTests {}

@ContextHierarchy(@ContextConfiguration(&quot;/spring/rest-ws-config.xml&quot;))
public class RestWebServiceTests extends AbstractWebTests {}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
@WebAppConfiguration
@ContextConfiguration(&quot;file:src/main/webapp/WEB-INF/applicationContext.xml&quot;)
abstract class AbstractWebTests

@ContextHierarchy(ContextConfiguration(&quot;/spring/soap-ws-config.xml&quot;))
class SoapWebServiceTests : AbstractWebTests()

@ContextHierarchy(ContextConfiguration(&quot;/spring/rest-ws-config.xml&quot;))
class RestWebServiceTests : AbstractWebTests()
</code></pre></div><p>Class hierarchy with merged context hierarchy configuration</p> <p>The classes in this example show the use of named hierarchy levels in order to merge the
configuration for specific levels in a context hierarchy. <code>BaseTests</code> defines two levels
in the hierarchy, <code>parent</code> and <code>child</code>. <code>ExtendedTests</code> extends <code>BaseTests</code> and instructs
the Spring TestContext Framework to merge the context configuration for the <code>child</code>hierarchy level, by ensuring that the names declared in the <code>name</code> attribute in<code>@ContextConfiguration</code> are both <code>child</code>. The result is that three application contexts
are loaded: one for <code>/app-config.xml</code>, one for <code>/user-config.xml</code>, and one for<code>{&quot;/user-config.xml&quot;, &quot;/order-config.xml&quot;}</code>. As with the previous example, the
application context loaded from <code>/app-config.xml</code> is set as the parent context for the
contexts loaded from <code>/user-config.xml</code> and <code>{&quot;/user-config.xml&quot;, &quot;/order-config.xml&quot;}</code>.
The following listing shows this configuration scenario:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
@ContextHierarchy({
    @ContextConfiguration(name = &quot;parent&quot;, locations = &quot;/app-config.xml&quot;),
    @ContextConfiguration(name = &quot;child&quot;, locations = &quot;/user-config.xml&quot;)
})
class BaseTests {}

@ContextHierarchy(
    @ContextConfiguration(name = &quot;child&quot;, locations = &quot;/order-config.xml&quot;)
)
class ExtendedTests extends BaseTests {}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
@ContextHierarchy(
    ContextConfiguration(name = &quot;parent&quot;, locations = [&quot;/app-config.xml&quot;]),
    ContextConfiguration(name = &quot;child&quot;, locations = [&quot;/user-config.xml&quot;]))
open class BaseTests {}

@ContextHierarchy(
    ContextConfiguration(name = &quot;child&quot;, locations = [&quot;/order-config.xml&quot;])
)
class ExtendedTests : BaseTests() {}
</code></pre></div><p>Class hierarchy with overridden context hierarchy configuration</p> <p>In contrast to the previous example, this example demonstrates how to override the
configuration for a given named level in a context hierarchy by setting the<code>inheritLocations</code> flag in <code>@ContextConfiguration</code> to <code>false</code>. Consequently, the
application context for <code>ExtendedTests</code> is loaded only from <code>/test-user-config.xml</code> and
has its parent set to the context loaded from <code>/app-config.xml</code>. The following listing
shows this configuration scenario:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
@ContextHierarchy({
    @ContextConfiguration(name = &quot;parent&quot;, locations = &quot;/app-config.xml&quot;),
    @ContextConfiguration(name = &quot;child&quot;, locations = &quot;/user-config.xml&quot;)
})
class BaseTests {}

@ContextHierarchy(
    @ContextConfiguration(
        name = &quot;child&quot;,
        locations = &quot;/test-user-config.xml&quot;,
        inheritLocations = false
))
class ExtendedTests extends BaseTests {}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
@ContextHierarchy(
    ContextConfiguration(name = &quot;parent&quot;, locations = [&quot;/app-config.xml&quot;]),
    ContextConfiguration(name = &quot;child&quot;, locations = [&quot;/user-config.xml&quot;]))
open class BaseTests {}

@ContextHierarchy(
        ContextConfiguration(
                name = &quot;child&quot;,
                locations = [&quot;/test-user-config.xml&quot;],
                inheritLocations = false
        ))
class ExtendedTests : BaseTests() {}
</code></pre></div><table><thead><tr><th></th> <th>Dirtying a context within a context hierarchy<br><br>If you use <code>@DirtiesContext</code> in a test whose context is configured as part of a<br>context hierarchy, you can use the <code>hierarchyMode</code> flag to control how the context cache<br>is cleared. For further details, see the discussion of <code>@DirtiesContext</code> in<a href="#spring-testing-annotation-dirtiescontext">Spring Testing Annotations</a> and the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/annotation/DirtiesContext.html" target="_blank" rel="noopener noreferrer"><code>@DirtiesContext</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> javadoc.</th></tr></thead> <tbody></tbody></table> <h4 id="_3-5-7-dependency-injection-of-test-fixtures"><a href="#_3-5-7-dependency-injection-of-test-fixtures" class="header-anchor">#</a> 3.5.7. Dependency Injection of Test Fixtures</h4> <p>When you use the <code>DependencyInjectionTestExecutionListener</code> (which is configured by
default), the dependencies of your test instances are injected from beans in the
application context that you configured with <code>@ContextConfiguration</code> or related
annotations. You may use setter injection, field injection, or both, depending on
which annotations you choose and whether you place them on setter methods or fields.
If you are using JUnit Jupiter you may also optionally use constructor injection
(see <a href="#testcontext-junit-jupiter-di">Dependency Injection with <code>SpringExtension</code></a>). For consistency with Spring’s annotation-based
injection support, you may also use Spring’s <code>@Autowired</code> annotation or the <code>@Inject</code>annotation from JSR-330 for field and setter injection.</p> <table><thead><tr><th></th> <th>For testing frameworks other than JUnit Jupiter, the TestContext framework does not<br>participate in instantiation of the test class. Thus, the use of <code>@Autowired</code> or<code>@Inject</code> for constructors has no effect for test classes.</th></tr></thead> <tbody></tbody></table> <table><thead><tr><th></th> <th>Although field injection is discouraged in production code, field injection is<br>actually quite natural in test code. The rationale for the difference is that you will<br>never instantiate your test class directly. Consequently, there is no need to be able to<br>invoke a <code>public</code> constructor or setter method on your test class.</th></tr></thead> <tbody></tbody></table> <p>Because <code>@Autowired</code> is used to perform <a href="/en/spring-framework/core.html#beans-factory-autowire">autowiring by
type</a>, if you have multiple bean definitions of the same type, you cannot rely on this
approach for those particular beans. In that case, you can use <code>@Autowired</code> in
conjunction with <code>@Qualifier</code>. You can also choose to use <code>@Inject</code> in conjunction with<code>@Named</code>. Alternatively, if your test class has access to its <code>ApplicationContext</code>, you
can perform an explicit lookup by using (for example) a call to<code>applicationContext.getBean(&quot;titleRepository&quot;, TitleRepository.class)</code>.</p> <p>If you do not want dependency injection applied to your test instances, do not annotate
fields or setter methods with <code>@Autowired</code> or <code>@Inject</code>. Alternatively, you can disable
dependency injection altogether by explicitly configuring your class with<code>@TestExecutionListeners</code> and omitting <code>DependencyInjectionTestExecutionListener.class</code>from the list of listeners.</p> <p>Consider the scenario of testing a <code>HibernateTitleRepository</code> class, as outlined in the<a href="#integration-testing-goals">Goals</a> section. The next two code listings demonstrate the
use of <code>@Autowired</code> on fields and setter methods. The application context configuration
is presented after all sample code listings.</p> <table><thead><tr><th></th> <th>The dependency injection behavior in the following code listings is not specific to JUnit<br>Jupiter. The same DI techniques can be used in conjunction with any supported testing<br>framework.<br><br>The following examples make calls to static assertion methods, such as <code>assertNotNull()</code>,<br>but without prepending the call with <code>Assertions</code>. In such cases, assume that the method<br>was properly imported through an <code>import static</code> declaration that is not shown in the<br>example.</th></tr></thead> <tbody></tbody></table> <p>The first code listing shows a JUnit Jupiter based implementation of the test class that
uses <code>@Autowired</code> for field injection:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
// specifies the Spring configuration to load for this test fixture
@ContextConfiguration(&quot;repository-config.xml&quot;)
class HibernateTitleRepositoryTests {

    // this instance will be dependency injected by type
    @Autowired
    HibernateTitleRepository titleRepository;

    @Test
    void findById() {
        Title title = titleRepository.findById(new Long(10));
        assertNotNull(title);
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
// specifies the Spring configuration to load for this test fixture
@ContextConfiguration(&quot;repository-config.xml&quot;)
class HibernateTitleRepositoryTests {

    // this instance will be dependency injected by type
    @Autowired
    lateinit var titleRepository: HibernateTitleRepository

    @Test
    fun findById() {
        val title = titleRepository.findById(10)
        assertNotNull(title)
    }
}
</code></pre></div><p>Alternatively, you can configure the class to use <code>@Autowired</code> for setter injection, as
follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
// specifies the Spring configuration to load for this test fixture
@ContextConfiguration(&quot;repository-config.xml&quot;)
class HibernateTitleRepositoryTests {

    // this instance will be dependency injected by type
    HibernateTitleRepository titleRepository;

    @Autowired
    void setTitleRepository(HibernateTitleRepository titleRepository) {
        this.titleRepository = titleRepository;
    }

    @Test
    void findById() {
        Title title = titleRepository.findById(new Long(10));
        assertNotNull(title);
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension::class)
// specifies the Spring configuration to load for this test fixture
@ContextConfiguration(&quot;repository-config.xml&quot;)
class HibernateTitleRepositoryTests {

    // this instance will be dependency injected by type
    lateinit var titleRepository: HibernateTitleRepository

    @Autowired
    fun setTitleRepository(titleRepository: HibernateTitleRepository) {
        this.titleRepository = titleRepository
    }

    @Test
    fun findById() {
        val title = titleRepository.findById(10)
        assertNotNull(title)
    }
}
</code></pre></div><p>The preceding code listings use the same XML context file referenced by the<code>@ContextConfiguration</code> annotation (that is, <code>repository-config.xml</code>). The following
shows this configuration:</p> <div class="language- extra-class"><pre class="language-text"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd&quot;&gt;

    &lt;!-- this bean will be injected into the HibernateTitleRepositoryTests class --&gt;
    &lt;bean id=&quot;titleRepository&quot; class=&quot;com.foo.repository.hibernate.HibernateTitleRepository&quot;&gt;
        &lt;property name=&quot;sessionFactory&quot; ref=&quot;sessionFactory&quot;/&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;sessionFactory&quot; class=&quot;org.springframework.orm.hibernate5.LocalSessionFactoryBean&quot;&gt;
        &lt;!-- configuration elided for brevity --&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
</code></pre></div><table><thead><tr><th></th> <th>If you are extending from a Spring-provided test base class that happens to use<code>@Autowired</code> on one of its setter methods, you might have multiple beans of the affected<br>type defined in your application context (for example, multiple <code>DataSource</code> beans). In<br>such a case, you can override the setter method and use the <code>@Qualifier</code> annotation to<br>indicate a specific target bean, as follows (but make sure to delegate to the overridden<br>method in the superclass as well):<br><br>Java<br><br><code>&lt;br/&gt;// ...&lt;br/&gt;&lt;br/&gt; @Autowired&lt;br/&gt; @Override&lt;br/&gt; public void setDataSource(@Qualifier(&quot;myDataSource&quot;) DataSource dataSource) {&lt;br/&gt; super.setDataSource(dataSource);&lt;br/&gt; }&lt;br/&gt;&lt;br/&gt;// ...&lt;br/&gt;</code><br><br>Kotlin<br><br><code>&lt;br/&gt;// ...&lt;br/&gt;&lt;br/&gt; @Autowired&lt;br/&gt; override fun setDataSource(@Qualifier(&quot;myDataSource&quot;) dataSource: DataSource) {&lt;br/&gt; super.setDataSource(dataSource)&lt;br/&gt; }&lt;br/&gt;&lt;br/&gt;// ...&lt;br/&gt;</code><br><br>The specified qualifier value indicates the specific <code>DataSource</code> bean to inject,<br>narrowing the set of type matches to a specific bean. Its value is matched against<code>&lt;qualifier&gt;</code> declarations within the corresponding <code>&lt;bean&gt;</code> definitions. The bean name<br>is used as a fallback qualifier value, so you can effectively also point to a specific<br>bean by name there (as shown earlier, assuming that <code>myDataSource</code> is the bean <code>id</code>).</th></tr></thead> <tbody></tbody></table> <h4 id="_3-5-8-testing-request-and-session-scoped-beans"><a href="#_3-5-8-testing-request-and-session-scoped-beans" class="header-anchor">#</a> 3.5.8. Testing Request- and Session-scoped Beans</h4> <p>Spring has supported <a href="/en/spring-framework/core.html#beans-factory-scopes-other">Request- and session-scoped
beans</a> since the early years, and you can test your request-scoped and session-scoped
beans by following these steps:</p> <ul><li><p>Ensure that a <code>WebApplicationContext</code> is loaded for your test by annotating your test
class with <code>@WebAppConfiguration</code>.</p></li> <li><p>Inject the mock request or session into your test instance and prepare your test
fixture as appropriate.</p></li> <li><p>Invoke your web component that you retrieved from the configured<code>WebApplicationContext</code> (with dependency injection).</p></li> <li><p>Perform assertions against the mocks.</p></li></ul> <p>The next code snippet shows the XML configuration for a login use case. Note that the<code>userService</code> bean has a dependency on a request-scoped <code>loginAction</code> bean. Also, the<code>LoginAction</code> is instantiated by using <a href="/en/spring-framework/core.html#expressions">SpEL expressions</a> that
retrieve the username and password from the current HTTP request. In our test, we want to
configure these request parameters through the mock managed by the TestContext framework.
The following listing shows the configuration for this use case:</p> <p>Request-scoped bean configuration</p> <div class="language- extra-class"><pre class="language-text"><code>&lt;beans&gt;

    &lt;bean id=&quot;userService&quot; class=&quot;com.example.SimpleUserService&quot;
            c:loginAction-ref=&quot;loginAction&quot;/&gt;

    &lt;bean id=&quot;loginAction&quot; class=&quot;com.example.LoginAction&quot;
            c:username=&quot;#{request.getParameter('user')}&quot;
            c:password=&quot;#{request.getParameter('pswd')}&quot;
            scope=&quot;request&quot;&gt;
        &lt;aop:scoped-proxy/&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
</code></pre></div><p>In <code>RequestScopedBeanTests</code>, we inject both the <code>UserService</code> (that is, the subject under
test) and the <code>MockHttpServletRequest</code> into our test instance. Within our<code>requestScope()</code> test method, we set up our test fixture by setting request parameters in
the provided <code>MockHttpServletRequest</code>. When the <code>loginUser()</code> method is invoked on our<code>userService</code>, we are assured that the user service has access to the request-scoped<code>loginAction</code> for the current <code>MockHttpServletRequest</code> (that is, the one in which we just
set parameters). We can then perform assertions against the results based on the known
inputs for the username and password. The following listing shows how to do so:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig
class RequestScopedBeanTests {

    @Autowired UserService userService;
    @Autowired MockHttpServletRequest request;

    @Test
    void requestScope() {
        request.setParameter(&quot;user&quot;, &quot;enigma&quot;);
        request.setParameter(&quot;pswd&quot;, &quot;$pr!ng&quot;);

        LoginResults results = userService.loginUser();
        // assert results
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig
class RequestScopedBeanTests {

    @Autowired lateinit var userService: UserService
    @Autowired lateinit var request: MockHttpServletRequest

    @Test
    fun requestScope() {
        request.setParameter(&quot;user&quot;, &quot;enigma&quot;)
        request.setParameter(&quot;pswd&quot;, &quot;\$pr!ng&quot;)

        val results = userService.loginUser()
        // assert results
    }
}
</code></pre></div><p>The following code snippet is similar to the one we saw earlier for a request-scoped
bean. However, this time, the <code>userService</code> bean has a dependency on a session-scoped<code>userPreferences</code> bean. Note that the <code>UserPreferences</code> bean is instantiated by using a
SpEL expression that retrieves the theme from the current HTTP session. In our test, we
need to configure a theme in the mock session managed by the TestContext framework. The
following example shows how to do so:</p> <p>Session-scoped bean configuration</p> <div class="language- extra-class"><pre class="language-text"><code>&lt;beans&gt;

    &lt;bean id=&quot;userService&quot; class=&quot;com.example.SimpleUserService&quot;
            c:userPreferences-ref=&quot;userPreferences&quot; /&gt;

    &lt;bean id=&quot;userPreferences&quot; class=&quot;com.example.UserPreferences&quot;
            c:theme=&quot;#{session.getAttribute('theme')}&quot;
            scope=&quot;session&quot;&gt;
        &lt;aop:scoped-proxy/&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
</code></pre></div><p>In <code>SessionScopedBeanTests</code>, we inject the <code>UserService</code> and the <code>MockHttpSession</code> into
our test instance. Within our <code>sessionScope()</code> test method, we set up our test fixture by
setting the expected <code>theme</code> attribute in the provided <code>MockHttpSession</code>. When the<code>processUserPreferences()</code> method is invoked on our <code>userService</code>, we are assured that
the user service has access to the session-scoped <code>userPreferences</code> for the current<code>MockHttpSession</code>, and we can perform assertions against the results based on the
configured theme. The following example shows how to do so:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig
class SessionScopedBeanTests {

    @Autowired UserService userService;
    @Autowired MockHttpSession session;

    @Test
    void sessionScope() throws Exception {
        session.setAttribute(&quot;theme&quot;, &quot;blue&quot;);

        Results results = userService.processUserPreferences();
        // assert results
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig
class SessionScopedBeanTests {

    @Autowired lateinit var userService: UserService
    @Autowired lateinit var session: MockHttpSession

    @Test
    fun sessionScope() {
        session.setAttribute(&quot;theme&quot;, &quot;blue&quot;)

        val results = userService.processUserPreferences()
        // assert results
    }
}
</code></pre></div><h4 id="_3-5-9-transaction-management"><a href="#_3-5-9-transaction-management" class="header-anchor">#</a> 3.5.9. Transaction Management</h4> <p>In the TestContext framework, transactions are managed by the<code>TransactionalTestExecutionListener</code>, which is configured by default, even if you do not
explicitly declare <code>@TestExecutionListeners</code> on your test class. To enable support for
transactions, however, you must configure a <code>PlatformTransactionManager</code> bean in the<code>ApplicationContext</code> that is loaded with <code>@ContextConfiguration</code> semantics (further
details are provided later). In addition, you must declare Spring’s <code>@Transactional</code>annotation either at the class or the method level for your tests.</p> <h5 id="test-managed-transactions"><a href="#test-managed-transactions" class="header-anchor">#</a> Test-managed Transactions</h5> <p>Test-managed transactions are transactions that are managed declaratively by using the<code>TransactionalTestExecutionListener</code> or programmatically by using <code>TestTransaction</code>(described later). You should not confuse such transactions with Spring-managed
transactions (those managed directly by Spring within the <code>ApplicationContext</code> loaded for
tests) or application-managed transactions (those managed programmatically within
application code that is invoked by tests). Spring-managed and application-managed
transactions typically participate in test-managed transactions. However, you should use
caution if Spring-managed or application-managed transactions are configured with any
propagation type other than <code>REQUIRED</code> or <code>SUPPORTS</code> (see the discussion on<a href="/en/spring-framework/data-access.html#tx-propagation">transaction propagation</a> for details).</p> <table><thead><tr><th></th> <th>Preemptive timeouts and test-managed transactions<br><br>Caution must be taken when using any form of preemptive timeouts from a testing framework<br>in conjunction with Spring’s test-managed transactions.<br><br>Specifically, Spring’s testing support binds transaction state to the current thread (via<br>a <code>java.lang.ThreadLocal</code> variable) <em>before</em> the current test method is invoked. If a<br>testing framework invokes the current test method in a new thread in order to support a<br>preemptive timeout, any actions performed within the current test method will <em>not</em> be<br>invoked within the test-managed transaction. Consequently, the result of any such actions<br>will not be rolled back with the test-managed transaction. On the contrary, such actions<br>will be committed to the persistent store — for example, a relational database — even<br>though the test-managed transaction is properly rolled back by Spring.<br><br>Situations in which this can occur include but are not limited to the following.<br><br>* JUnit 4’s <code>@Test(timeout = …​)</code> support and <code>TimeOut</code> rule<br><br>* JUnit Jupiter’s <code>assertTimeoutPreemptively(…​)</code> methods in the<code>org.junit.jupiter.api.Assertions</code> class<br><br>* TestNG’s <code>@Test(timeOut = …​)</code> support</th></tr></thead> <tbody></tbody></table> <h5 id="enabling-and-disabling-transactions"><a href="#enabling-and-disabling-transactions" class="header-anchor">#</a> Enabling and Disabling Transactions</h5> <p>Annotating a test method with <code>@Transactional</code> causes the test to be run within a
transaction that is, by default, automatically rolled back after completion of the test.
If a test class is annotated with <code>@Transactional</code>, each test method within that class
hierarchy runs within a transaction. Test methods that are not annotated with<code>@Transactional</code> (at the class or method level) are not run within a transaction. Note
that <code>@Transactional</code> is not supported on test lifecycle methods — for example, methods
annotated with JUnit Jupiter’s <code>@BeforeAll</code>, <code>@BeforeEach</code>, etc. Furthermore, tests that
are annotated with <code>@Transactional</code> but have the <code>propagation</code> attribute set to<code>NOT_SUPPORTED</code> or <code>NEVER</code> are not run within a transaction.</p> <table><thead><tr><th>Attribute</th> <th>Supported for test-managed transactions</th></tr></thead> <tbody><tr><td><code>value</code> and <code>transactionManager</code></td> <td>yes</td></tr> <tr><td><code>propagation</code></td> <td>only <code>Propagation.NOT_SUPPORTED</code> and <code>Propagation.NEVER</code> are supported</td></tr> <tr><td><code>isolation</code></td> <td>no</td></tr> <tr><td><code>timeout</code></td> <td>no</td></tr> <tr><td><code>readOnly</code></td> <td>no</td></tr> <tr><td><code>rollbackFor</code> and <code>rollbackForClassName</code></td> <td>no: use <code>TestTransaction.flagForRollback()</code> instead</td></tr> <tr><td><code>noRollbackFor</code> and <code>noRollbackForClassName</code></td> <td>no: use <code>TestTransaction.flagForCommit()</code> instead</td></tr></tbody></table> <table><thead><tr><th></th> <th>Method-level lifecycle methods — for example, methods annotated with JUnit Jupiter’s<code>@BeforeEach</code> or <code>@AfterEach</code> — are run within a test-managed transaction. On the other<br>hand, suite-level and class-level lifecycle methods — for example, methods annotated with<br>JUnit Jupiter’s <code>@BeforeAll</code> or <code>@AfterAll</code> and methods annotated with TestNG’s<code>@BeforeSuite</code>, <code>@AfterSuite</code>, <code>@BeforeClass</code>, or <code>@AfterClass</code> — are <em>not</em> run within a<br>test-managed transaction.<br><br>If you need to run code in a suite-level or class-level lifecycle method within a<br>transaction, you may wish to inject a corresponding <code>PlatformTransactionManager</code> into<br>your test class and then use that with a <code>TransactionTemplate</code> for programmatic<br>transaction management.</th></tr></thead> <tbody></tbody></table> <p>Note that <a href="#testcontext-support-classes-junit4"><code>AbstractTransactionalJUnit4SpringContextTests</code></a> and<a href="#testcontext-support-classes-testng"><code>AbstractTransactionalTestNGSpringContextTests</code></a>are preconfigured for transactional support at the class level.</p> <p>The following example demonstrates a common scenario for writing an integration test for
a Hibernate-based <code>UserRepository</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig.class)
@Transactional
class HibernateUserRepositoryTests {

    @Autowired
    HibernateUserRepository repository;

    @Autowired
    SessionFactory sessionFactory;

    JdbcTemplate jdbcTemplate;

    @Autowired
    void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Test
    void createUser() {
        // track initial state in test database:
        final int count = countRowsInTable(&quot;user&quot;);

        User user = new User(...);
        repository.save(user);

        // Manual flush is required to avoid false positive in test
        sessionFactory.getCurrentSession().flush();
        assertNumUsers(count + 1);
    }

    private int countRowsInTable(String tableName) {
        return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName);
    }

    private void assertNumUsers(int expected) {
        assertEquals(&quot;Number of rows in the [user] table.&quot;, expected, countRowsInTable(&quot;user&quot;));
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig::class)
@Transactional
class HibernateUserRepositoryTests {

    @Autowired
    lateinit var repository: HibernateUserRepository

    @Autowired
    lateinit var sessionFactory: SessionFactory

    lateinit var jdbcTemplate: JdbcTemplate

    @Autowired
    fun setDataSource(dataSource: DataSource) {
        this.jdbcTemplate = JdbcTemplate(dataSource)
    }

    @Test
    fun createUser() {
        // track initial state in test database:
        val count = countRowsInTable(&quot;user&quot;)

        val user = User()
        repository.save(user)

        // Manual flush is required to avoid false positive in test
        sessionFactory.getCurrentSession().flush()
        assertNumUsers(count + 1)
    }

    private fun countRowsInTable(tableName: String): Int {
        return JdbcTestUtils.countRowsInTable(jdbcTemplate, tableName)
    }

    private fun assertNumUsers(expected: Int) {
        assertEquals(&quot;Number of rows in the [user] table.&quot;, expected, countRowsInTable(&quot;user&quot;))
    }
}
</code></pre></div><p>As explained in <a href="#testcontext-tx-rollback-and-commit-behavior">Transaction Rollback and Commit Behavior</a>, there is no need to
clean up the database after the <code>createUser()</code> method runs, since any changes made to the
database are automatically rolled back by the <code>TransactionalTestExecutionListener</code>.</p> <h5 id="transaction-rollback-and-commit-behavior"><a href="#transaction-rollback-and-commit-behavior" class="header-anchor">#</a> Transaction Rollback and Commit Behavior</h5> <p>By default, test transactions will be automatically rolled back after completion of the
test; however, transactional commit and rollback behavior can be configured declaratively
via the <code>@Commit</code> and <code>@Rollback</code> annotations. See the corresponding entries in the<a href="#integration-testing-annotations">annotation support</a> section for further details.</p> <h5 id="programmatic-transaction-management"><a href="#programmatic-transaction-management" class="header-anchor">#</a> Programmatic Transaction Management</h5> <p>You can interact with test-managed transactions programmatically by using the static
methods in <code>TestTransaction</code>. For example, you can use <code>TestTransaction</code> within test
methods, before methods, and after methods to start or end the current test-managed
transaction or to configure the current test-managed transaction for rollback or commit.
Support for <code>TestTransaction</code> is automatically available whenever the<code>TransactionalTestExecutionListener</code> is enabled.</p> <p>The following example demonstrates some of the features of <code>TestTransaction</code>. See the
javadoc for <a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/transaction/TestTransaction.html" target="_blank" rel="noopener noreferrer"><code>TestTransaction</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>for further details.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration(classes = TestConfig.class)
public class ProgrammaticTransactionManagementTests extends
        AbstractTransactionalJUnit4SpringContextTests {

    @Test
    public void transactionalTest() {
        // assert initial state in test database:
        assertNumUsers(2);

        deleteFromTables(&quot;user&quot;);

        // changes to the database will be committed!
        TestTransaction.flagForCommit();
        TestTransaction.end();
        assertFalse(TestTransaction.isActive());
        assertNumUsers(0);

        TestTransaction.start();
        // perform other actions against the database that will
        // be automatically rolled back after the test completes...
    }

    protected void assertNumUsers(int expected) {
        assertEquals(&quot;Number of rows in the [user] table.&quot;, expected, countRowsInTable(&quot;user&quot;));
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ContextConfiguration(classes = [TestConfig::class])
class ProgrammaticTransactionManagementTests : AbstractTransactionalJUnit4SpringContextTests() {

    @Test
    fun transactionalTest() {
        // assert initial state in test database:
        assertNumUsers(2)

        deleteFromTables(&quot;user&quot;)

        // changes to the database will be committed!
        TestTransaction.flagForCommit()
        TestTransaction.end()
        assertFalse(TestTransaction.isActive())
        assertNumUsers(0)

        TestTransaction.start()
        // perform other actions against the database that will
        // be automatically rolled back after the test completes...
    }

    protected fun assertNumUsers(expected: Int) {
        assertEquals(&quot;Number of rows in the [user] table.&quot;, expected, countRowsInTable(&quot;user&quot;))
    }
}
</code></pre></div><h5 id="running-code-outside-of-a-transaction"><a href="#running-code-outside-of-a-transaction" class="header-anchor">#</a> Running Code Outside of a Transaction</h5> <p>Occasionally, you may need to run certain code before or after a transactional test
method but outside the transactional context — for example, to verify the initial
database state prior to running your test or to verify expected transactional commit
behavior after your test runs (if the test was configured to commit the transaction).<code>TransactionalTestExecutionListener</code> supports the <code>@BeforeTransaction</code> and<code>@AfterTransaction</code> annotations for exactly such scenarios. You can annotate any <code>void</code>method in a test class or any <code>void</code> default method in a test interface with one of these
annotations, and the <code>TransactionalTestExecutionListener</code> ensures that your before
transaction method or after transaction method runs at the appropriate time.</p> <table><thead><tr><th></th> <th>Any before methods (such as methods annotated with JUnit Jupiter’s <code>@BeforeEach</code>)<br>and any after methods (such as methods annotated with JUnit Jupiter’s <code>@AfterEach</code>) are<br>run within a transaction. In addition, methods annotated with <code>@BeforeTransaction</code> or<code>@AfterTransaction</code> are not run for test methods that are not configured to run within a<br>transaction.</th></tr></thead> <tbody></tbody></table> <h5 id="configuring-a-transaction-manager"><a href="#configuring-a-transaction-manager" class="header-anchor">#</a> Configuring a Transaction Manager</h5> <p><code>TransactionalTestExecutionListener</code> expects a <code>PlatformTransactionManager</code> bean to be
defined in the Spring <code>ApplicationContext</code> for the test. If there are multiple instances
of <code>PlatformTransactionManager</code> within the test’s <code>ApplicationContext</code>, you can declare a
qualifier by using <code>@Transactional(&quot;myTxMgr&quot;)</code> or <code>@Transactional(transactionManager = &quot;myTxMgr&quot;)</code>, or <code>TransactionManagementConfigurer</code> can be implemented by an<code>@Configuration</code> class. Consult the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/transaction/TestContextTransactionUtils.html#retrieveTransactionManager-org.springframework.test.context.TestContext-java.lang.String-" target="_blank" rel="noopener noreferrer">javadoc
for <code>TestContextTransactionUtils.retrieveTransactionManager()</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> for details on the
algorithm used to look up a transaction manager in the test’s <code>ApplicationContext</code>.</p> <h5 id="demonstration-of-all-transaction-related-annotations"><a href="#demonstration-of-all-transaction-related-annotations" class="header-anchor">#</a> Demonstration of All Transaction-related Annotations</h5> <p>The following JUnit Jupiter based example displays a fictitious integration testing
scenario that highlights all transaction-related annotations. The example is not intended
to demonstrate best practices but rather to demonstrate how these annotations can be
used. See the <a href="#integration-testing-annotations">annotation support</a> section for further
information and configuration examples. <a href="#testcontext-executing-sql-declaratively-tx">Transaction management for <code>@Sql</code></a> contains an additional example that uses <code>@Sql</code> for
declarative SQL script execution with default transaction rollback semantics. The
following example shows the relevant annotations:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig
@Transactional(transactionManager = &quot;txMgr&quot;)
@Commit
class FictitiousTransactionalTest {

    @BeforeTransaction
    void verifyInitialDatabaseState() {
        // logic to verify the initial state before a transaction is started
    }

    @BeforeEach
    void setUpTestDataWithinTransaction() {
        // set up test data within the transaction
    }

    @Test
    // overrides the class-level @Commit setting
    @Rollback
    void modifyDatabaseWithinTransaction() {
        // logic which uses the test data and modifies database state
    }

    @AfterEach
    void tearDownWithinTransaction() {
        // run &quot;tear down&quot; logic within the transaction
    }

    @AfterTransaction
    void verifyFinalDatabaseState() {
        // logic to verify the final state after transaction has rolled back
    }

}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig
@Transactional(transactionManager = &quot;txMgr&quot;)
@Commit
class FictitiousTransactionalTest {

    @BeforeTransaction
    fun verifyInitialDatabaseState() {
        // logic to verify the initial state before a transaction is started
    }

    @BeforeEach
    fun setUpTestDataWithinTransaction() {
        // set up test data within the transaction
    }

    @Test
    // overrides the class-level @Commit setting
    @Rollback
    fun modifyDatabaseWithinTransaction() {
        // logic which uses the test data and modifies database state
    }

    @AfterEach
    fun tearDownWithinTransaction() {
        // run &quot;tear down&quot; logic within the transaction
    }

    @AfterTransaction
    fun verifyFinalDatabaseState() {
        // logic to verify the final state after transaction has rolled back
    }

}
</code></pre></div><table><thead><tr><th></th> <th>Avoid false positives when testing ORM code<br><br>When you test application code that manipulates the state of a Hibernate session or JPA<br>persistence context, make sure to flush the underlying unit of work within test methods<br>that run that code. Failing to flush the underlying unit of work can produce false<br>positives: Your test passes, but the same code throws an exception in a live, production<br>environment. Note that this applies to any ORM framework that maintains an in-memory unit<br>of work. In the following Hibernate-based example test case, one method demonstrates a<br>false positive, and the other method correctly exposes the results of flushing the<br>session:<br><br>Java<br><br><code>&lt;br/&gt;// ...&lt;br/&gt;&lt;br/&gt;@Autowired&lt;br/&gt;SessionFactory sessionFactory;&lt;br/&gt;&lt;br/&gt;@Transactional&lt;br/&gt;@Test // no expected exception!&lt;br/&gt;public void falsePositive() {&lt;br/&gt; updateEntityInHibernateSession();&lt;br/&gt; // False positive: an exception will be thrown once the Hibernate&lt;br/&gt; // Session is finally flushed (i.e., in production code)&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;@Transactional&lt;br/&gt;@Test(expected = ...)&lt;br/&gt;public void updateWithSessionFlush() {&lt;br/&gt; updateEntityInHibernateSession();&lt;br/&gt; // Manual flush is required to avoid false positive in test&lt;br/&gt; sessionFactory.getCurrentSession().flush();&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;// ...&lt;br/&gt;</code><br><br>Kotlin<br><br><code>&lt;br/&gt;// ...&lt;br/&gt;&lt;br/&gt;@Autowired&lt;br/&gt;lateinit var sessionFactory: SessionFactory&lt;br/&gt;&lt;br/&gt;@Transactional&lt;br/&gt;@Test // no expected exception!&lt;br/&gt;fun falsePositive() {&lt;br/&gt; updateEntityInHibernateSession()&lt;br/&gt; // False positive: an exception will be thrown once the Hibernate&lt;br/&gt; // Session is finally flushed (i.e., in production code)&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;@Transactional&lt;br/&gt;@Test(expected = ...)&lt;br/&gt;fun updateWithSessionFlush() {&lt;br/&gt; updateEntityInHibernateSession()&lt;br/&gt; // Manual flush is required to avoid false positive in test&lt;br/&gt; sessionFactory.getCurrentSession().flush()&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;// ...&lt;br/&gt;</code><br><br>The following example shows matching methods for JPA:<br><br>Java<br><br><code>&lt;br/&gt;// ...&lt;br/&gt;&lt;br/&gt;@PersistenceContext&lt;br/&gt;EntityManager entityManager;&lt;br/&gt;&lt;br/&gt;@Transactional&lt;br/&gt;@Test // no expected exception!&lt;br/&gt;public void falsePositive() {&lt;br/&gt; updateEntityInJpaPersistenceContext();&lt;br/&gt; // False positive: an exception will be thrown once the JPA&lt;br/&gt; // EntityManager is finally flushed (i.e., in production code)&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;@Transactional&lt;br/&gt;@Test(expected = ...)&lt;br/&gt;public void updateWithEntityManagerFlush() {&lt;br/&gt; updateEntityInJpaPersistenceContext();&lt;br/&gt; // Manual flush is required to avoid false positive in test&lt;br/&gt; entityManager.flush();&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;// ...&lt;br/&gt;</code><br><br>Kotlin<br><br><code>&lt;br/&gt;// ...&lt;br/&gt;&lt;br/&gt;@PersistenceContext&lt;br/&gt;lateinit var entityManager:EntityManager&lt;br/&gt;&lt;br/&gt;@Transactional&lt;br/&gt;@Test // no expected exception!&lt;br/&gt;fun falsePositive() {&lt;br/&gt; updateEntityInJpaPersistenceContext()&lt;br/&gt; // False positive: an exception will be thrown once the JPA&lt;br/&gt; // EntityManager is finally flushed (i.e., in production code)&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;@Transactional&lt;br/&gt;@Test(expected = ...)&lt;br/&gt;void updateWithEntityManagerFlush() {&lt;br/&gt; updateEntityInJpaPersistenceContext()&lt;br/&gt; // Manual flush is required to avoid false positive in test&lt;br/&gt; entityManager.flush()&lt;br/&gt;}&lt;br/&gt;&lt;br/&gt;// ...&lt;br/&gt;</code></th></tr></thead> <tbody></tbody></table> <h4 id="_3-5-10-executing-sql-scripts"><a href="#_3-5-10-executing-sql-scripts" class="header-anchor">#</a> 3.5.10. Executing SQL Scripts</h4> <p>When writing integration tests against a relational database, it is often beneficial to
run SQL scripts to modify the database schema or insert test data into tables. The<code>spring-jdbc</code> module provides support for <em>initializing</em> an embedded or existing database
by executing SQL scripts when the Spring <code>ApplicationContext</code> is loaded. See<a href="/en/spring-framework/data-access.html#jdbc-embedded-database-support">Embedded database support</a> and<a href="/en/spring-framework/data-access.html#jdbc-embedded-database-dao-testing">Testing data access logic with an
embedded database</a> for details.</p> <p>Although it is very useful to initialize a database for testing <em>once</em> when the<code>ApplicationContext</code> is loaded, sometimes it is essential to be able to modify the
database <em>during</em> integration tests. The following sections explain how to run SQL
scripts programmatically and declaratively during integration tests.</p> <h5 id="executing-sql-scripts-programmatically"><a href="#executing-sql-scripts-programmatically" class="header-anchor">#</a> Executing SQL scripts programmatically</h5> <p>Spring provides the following options for executing SQL scripts programmatically within
integration test methods.</p> <ul><li><p><code>org.springframework.jdbc.datasource.init.ScriptUtils</code></p></li> <li><p><code>org.springframework.jdbc.datasource.init.ResourceDatabasePopulator</code></p></li> <li><p><code>org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests</code></p></li> <li><p><code>org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests</code></p></li></ul> <p><code>ScriptUtils</code> provides a collection of static utility methods for working with SQL
scripts and is mainly intended for internal use within the framework. However, if you
require full control over how SQL scripts are parsed and run, <code>ScriptUtils</code> may suit
your needs better than some of the other alternatives described later. See the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/jdbc/datasource/init/ScriptUtils.html" target="_blank" rel="noopener noreferrer">javadoc<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> for individual
methods in <code>ScriptUtils</code> for further details.</p> <p><code>ResourceDatabasePopulator</code> provides an object-based API for programmatically populating,
initializing, or cleaning up a database by using SQL scripts defined in external
resources. <code>ResourceDatabasePopulator</code> provides options for configuring the character
encoding, statement separator, comment delimiters, and error handling flags used when
parsing and running the scripts. Each of the configuration options has a reasonable
default value. See the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.html" target="_blank" rel="noopener noreferrer">javadoc<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> for
details on default values. To run the scripts configured in a<code>ResourceDatabasePopulator</code>, you can invoke either the <code>populate(Connection)</code> method to
run the populator against a <code>java.sql.Connection</code> or the <code>execute(DataSource)</code> method
to run the populator against a <code>javax.sql.DataSource</code>. The following example
specifies SQL scripts for a test schema and test data, sets the statement separator to<code>@@</code>, and run the scripts against a <code>DataSource</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
void databaseTest() {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScripts(
            new ClassPathResource(&quot;test-schema.sql&quot;),
            new ClassPathResource(&quot;test-data.sql&quot;));
    populator.setSeparator(&quot;@@&quot;);
    populator.execute(this.dataSource);
    // run code that uses the test schema and data
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
fun databaseTest() {
    val populator = ResourceDatabasePopulator()
    populator.addScripts(
            ClassPathResource(&quot;test-schema.sql&quot;),
            ClassPathResource(&quot;test-data.sql&quot;))
    populator.setSeparator(&quot;@@&quot;)
    populator.execute(dataSource)
    // run code that uses the test schema and data
}
</code></pre></div><p>Note that <code>ResourceDatabasePopulator</code> internally delegates to <code>ScriptUtils</code> for parsing
and running SQL scripts. Similarly, the <code>executeSqlScript(..)</code> methods in<a href="#testcontext-support-classes-junit4"><code>AbstractTransactionalJUnit4SpringContextTests</code></a>and <a href="#testcontext-support-classes-testng"><code>AbstractTransactionalTestNGSpringContextTests</code></a>internally use a <code>ResourceDatabasePopulator</code> to run SQL scripts. See the Javadoc for the
various <code>executeSqlScript(..)</code> methods for further details.</p> <h5 id="executing-sql-scripts-declaratively-with-sql"><a href="#executing-sql-scripts-declaratively-with-sql" class="header-anchor">#</a> Executing SQL scripts declaratively with @Sql</h5> <p>In addition to the aforementioned mechanisms for running SQL scripts programmatically,
you can declaratively configure SQL scripts in the Spring TestContext Framework.
Specifically, you can declare the <code>@Sql</code> annotation on a test class or test method to
configure individual SQL statements or the resource paths to SQL scripts that should be
run against a given database before or after an integration test method. Support for<code>@Sql</code> is provided by the <code>SqlScriptsTestExecutionListener</code>, which is enabled by default.</p> <table><thead><tr><th></th> <th>Method-level <code>@Sql</code> declarations override class-level declarations by default. As<br>of Spring Framework 5.2, however, this behavior may be configured per test class or per<br>test method via <code>@SqlMergeMode</code>. See<a href="#testcontext-executing-sql-declaratively-script-merging">Merging and Overriding Configuration with <code>@SqlMergeMode</code></a> for further details.</th></tr></thead> <tbody></tbody></table> <h6 id="path-resource-semantics"><a href="#path-resource-semantics" class="header-anchor">#</a> Path Resource Semantics</h6> <p>Each path is interpreted as a Spring <code>Resource</code>. A plain path (for example,<code>&quot;schema.sql&quot;</code>) is treated as a classpath resource that is relative to the package in
which the test class is defined. A path starting with a slash is treated as an absolute
classpath resource (for example, <code>&quot;/org/example/schema.sql&quot;</code>). A path that references a
URL (for example, a path prefixed with <code>classpath:</code>, <code>file:</code>, <code>http:</code>) is loaded by using
the specified resource protocol.</p> <p>The following example shows how to use <code>@Sql</code> at the class level and at the method level
within a JUnit Jupiter based integration test class:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig
@Sql(&quot;/test-schema.sql&quot;)
class DatabaseTests {

    @Test
    void emptySchemaTest() {
        // run code that uses the test schema without any test data
    }

    @Test
    @Sql({&quot;/test-schema.sql&quot;, &quot;/test-user-data.sql&quot;})
    void userTest() {
        // run code that uses the test schema and test data
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig
@Sql(&quot;/test-schema.sql&quot;)
class DatabaseTests {

    @Test
    fun emptySchemaTest() {
        // run code that uses the test schema without any test data
    }

    @Test
    @Sql(&quot;/test-schema.sql&quot;, &quot;/test-user-data.sql&quot;)
    fun userTest() {
        // run code that uses the test schema and test data
    }
}
</code></pre></div><h6 id="default-script-detection"><a href="#default-script-detection" class="header-anchor">#</a> Default Script Detection</h6> <p>If no SQL scripts or statements are specified, an attempt is made to detect a <code>default</code>script, depending on where <code>@Sql</code> is declared. If a default cannot be detected, an<code>IllegalStateException</code> is thrown.</p> <ul><li><p>Class-level declaration: If the annotated test class is <code>com.example.MyTest</code>, the
corresponding default script is <code>classpath:com/example/MyTest.sql</code>.</p></li> <li><p>Method-level declaration: If the annotated test method is named <code>testMethod()</code> and is
defined in the class <code>com.example.MyTest</code>, the corresponding default script is<code>classpath:com/example/MyTest.testMethod.sql</code>.</p></li></ul> <h6 id="declaring-multiple-sql-sets"><a href="#declaring-multiple-sql-sets" class="header-anchor">#</a> Declaring Multiple <code>@Sql</code> Sets</h6> <p>If you need to configure multiple sets of SQL scripts for a given test class or test
method but with different syntax configuration, different error handling rules, or
different execution phases per set, you can declare multiple instances of <code>@Sql</code>. With
Java 8, you can use <code>@Sql</code> as a repeatable annotation. Otherwise, you can use the<code>@SqlGroup</code> annotation as an explicit container for declaring multiple instances of<code>@Sql</code>.</p> <p>The following example shows how to use <code>@Sql</code> as a repeatable annotation with Java 8:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
@Sql(scripts = &quot;/test-schema.sql&quot;, config = @SqlConfig(commentPrefix = &quot;`&quot;))
@Sql(&quot;/test-user-data.sql&quot;)
void userTest() {
    // run code that uses the test schema and test data
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// Repeatable annotations with non-SOURCE retention are not yet supported by Kotlin
</code></pre></div><p>In the scenario presented in the preceding example, the <code>test-schema.sql</code> script uses a
different syntax for single-line comments.</p> <p>The following example is identical to the preceding example, except that the <code>@Sql</code>declarations are grouped together within <code>@SqlGroup</code>. With Java 8 and above, the use of<code>@SqlGroup</code> is optional, but you may need to use <code>@SqlGroup</code> for compatibility with
other JVM languages such as Kotlin.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
@SqlGroup({
    @Sql(scripts = &quot;/test-schema.sql&quot;, config = @SqlConfig(commentPrefix = &quot;`&quot;)),
    @Sql(&quot;/test-user-data.sql&quot;)
)}
void userTest() {
    // run code that uses the test schema and test data
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
@SqlGroup(
    Sql(&quot;/test-schema.sql&quot;, config = SqlConfig(commentPrefix = &quot;`&quot;)),
    Sql(&quot;/test-user-data.sql&quot;))
fun userTest() {
    // Run code that uses the test schema and test data
}
</code></pre></div><h6 id="script-execution-phases"><a href="#script-execution-phases" class="header-anchor">#</a> Script Execution Phases</h6> <p>By default, SQL scripts are run before the corresponding test method. However, if
you need to run a particular set of scripts after the test method (for example, to clean
up database state), you can use the <code>executionPhase</code> attribute in <code>@Sql</code>, as the
following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
@Sql(
    scripts = &quot;create-test-data.sql&quot;,
    config = @SqlConfig(transactionMode = ISOLATED)
)
@Sql(
    scripts = &quot;delete-test-data.sql&quot;,
    config = @SqlConfig(transactionMode = ISOLATED),
    executionPhase = AFTER_TEST_METHOD
)
void userTest() {
    // run code that needs the test data to be committed
    // to the database outside of the test's transaction
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
@SqlGroup(
    Sql(&quot;create-test-data.sql&quot;,
        config = SqlConfig(transactionMode = ISOLATED)),
    Sql(&quot;delete-test-data.sql&quot;,
        config = SqlConfig(transactionMode = ISOLATED),
        executionPhase = AFTER_TEST_METHOD))
fun userTest() {
    // run code that needs the test data to be committed
    // to the database outside of the test's transaction
}
</code></pre></div><p>Note that <code>ISOLATED</code> and <code>AFTER_TEST_METHOD</code> are statically imported from<code>Sql.TransactionMode</code> and <code>Sql.ExecutionPhase</code>, respectively.</p> <h6 id="script-configuration-with-sqlconfig"><a href="#script-configuration-with-sqlconfig" class="header-anchor">#</a> Script Configuration with <code>@SqlConfig</code></h6> <p>You can configure script parsing and error handling by using the <code>@SqlConfig</code> annotation.
When declared as a class-level annotation on an integration test class, <code>@SqlConfig</code>serves as global configuration for all SQL scripts within the test class hierarchy. When
declared directly by using the <code>config</code> attribute of the <code>@Sql</code> annotation, <code>@SqlConfig</code>serves as local configuration for the SQL scripts declared within the enclosing <code>@Sql</code>annotation. Every attribute in <code>@SqlConfig</code> has an implicit default value, which is
documented in the javadoc of the corresponding attribute. Due to the rules defined for
annotation attributes in the Java Language Specification, it is, unfortunately, not
possible to assign a value of <code>null</code> to an annotation attribute. Thus, in order to
support overrides of inherited global configuration, <code>@SqlConfig</code> attributes have an
explicit default value of either <code>&quot;&quot;</code> (for Strings), <code>{}</code> (for arrays), or <code>DEFAULT</code> (for
enumerations). This approach lets local declarations of <code>@SqlConfig</code> selectively override
individual attributes from global declarations of <code>@SqlConfig</code> by providing a value other
than <code>&quot;&quot;</code>, <code>{}</code>, or <code>DEFAULT</code>. Global <code>@SqlConfig</code> attributes are inherited whenever
local <code>@SqlConfig</code> attributes do not supply an explicit value other than <code>&quot;&quot;</code>, <code>{}</code>, or<code>DEFAULT</code>. Explicit local configuration, therefore, overrides global configuration.</p> <p>The configuration options provided by <code>@Sql</code> and <code>@SqlConfig</code> are equivalent to those
supported by <code>ScriptUtils</code> and <code>ResourceDatabasePopulator</code> but are a superset of those
provided by the <code>&lt;jdbc:initialize-database/&gt;</code> XML namespace element. See the javadoc of
individual attributes in <a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/jdbc/Sql.html" target="_blank" rel="noopener noreferrer"><code>@Sql</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> and<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/jdbc/SqlConfig.html" target="_blank" rel="noopener noreferrer"><code>@SqlConfig</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> for details.</p> <p><strong>Transaction management for <code>@Sql</code></strong></p> <p>By default, the <code>SqlScriptsTestExecutionListener</code> infers the desired transaction
semantics for scripts configured by using <code>@Sql</code>. Specifically, SQL scripts are run
without a transaction, within an existing Spring-managed transaction (for example, a
transaction managed by the <code>TransactionalTestExecutionListener</code> for a test annotated with<code>@Transactional</code>), or within an isolated transaction, depending on the configured value
of the <code>transactionMode</code> attribute in <code>@SqlConfig</code> and the presence of a<code>PlatformTransactionManager</code> in the test’s <code>ApplicationContext</code>. As a bare minimum,
however, a <code>javax.sql.DataSource</code> must be present in the test’s <code>ApplicationContext</code>.</p> <p>If the algorithms used by <code>SqlScriptsTestExecutionListener</code> to detect a <code>DataSource</code> and<code>PlatformTransactionManager</code> and infer the transaction semantics do not suit your needs,
you can specify explicit names by setting the <code>dataSource</code> and <code>transactionManager</code>attributes of <code>@SqlConfig</code>. Furthermore, you can control the transaction propagation
behavior by setting the <code>transactionMode</code> attribute of <code>@SqlConfig</code> (for example, whether
scripts should be run in an isolated transaction). Although a thorough discussion of all
supported options for transaction management with <code>@Sql</code> is beyond the scope of this
reference manual, the javadoc for<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/jdbc/SqlConfig.html" target="_blank" rel="noopener noreferrer"><code>@SqlConfig</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> and<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/jdbc/SqlScriptsTestExecutionListener.html" target="_blank" rel="noopener noreferrer"><code>SqlScriptsTestExecutionListener</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>provide detailed information, and the following example shows a typical testing scenario
that uses JUnit Jupiter and transactional tests with <code>@Sql</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestDatabaseConfig.class)
@Transactional
class TransactionalSqlScriptsTests {

    final JdbcTemplate jdbcTemplate;

    @Autowired
    TransactionalSqlScriptsTests(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Test
    @Sql(&quot;/test-data.sql&quot;)
    void usersTest() {
        // verify state in test database:
        assertNumUsers(2);
        // run code that uses the test data...
    }

    int countRowsInTable(String tableName) {
        return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName);
    }

    void assertNumUsers(int expected) {
        assertEquals(expected, countRowsInTable(&quot;user&quot;),
            &quot;Number of rows in the [user] table.&quot;);
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestDatabaseConfig::class)
@Transactional
class TransactionalSqlScriptsTests @Autowired constructor(dataSource: DataSource) {

    val jdbcTemplate: JdbcTemplate = JdbcTemplate(dataSource)

    @Test
    @Sql(&quot;/test-data.sql&quot;)
    fun usersTest() {
        // verify state in test database:
        assertNumUsers(2)
        // run code that uses the test data...
    }

    fun countRowsInTable(tableName: String): Int {
        return JdbcTestUtils.countRowsInTable(jdbcTemplate, tableName)
    }

    fun assertNumUsers(expected: Int) {
        assertEquals(expected, countRowsInTable(&quot;user&quot;),
                &quot;Number of rows in the [user] table.&quot;)
    }
}
</code></pre></div><p>Note that there is no need to clean up the database after the <code>usersTest()</code> method is
run, since any changes made to the database (either within the test method or within the<code>/test-data.sql</code> script) are automatically rolled back by the<code>TransactionalTestExecutionListener</code> (see <a href="#testcontext-tx">transaction management</a> for
details).</p> <h6 id="merging-and-overriding-configuration-with-sqlmergemode"><a href="#merging-and-overriding-configuration-with-sqlmergemode" class="header-anchor">#</a> Merging and Overriding Configuration with <code>@SqlMergeMode</code></h6> <p>As of Spring Framework 5.2, it is possible to merge method-level <code>@Sql</code> declarations with
class-level declarations. For example, this allows you to provide the configuration for a
database schema or some common test data once per test class and then provide additional,
use case specific test data per test method. To enable <code>@Sql</code> merging, annotate either
your test class or test method with <code>@SqlMergeMode(MERGE)</code>. To disable merging for a
specific test method (or specific test subclass), you can switch back to the default mode
via <code>@SqlMergeMode(OVERRIDE)</code>. Consult the <a href="#spring-testing-annotation-sqlmergemode"><code>@SqlMergeMode</code> annotation documentation section</a> for examples and further details.</p> <h4 id="_3-5-11-parallel-test-execution"><a href="#_3-5-11-parallel-test-execution" class="header-anchor">#</a> 3.5.11. Parallel Test Execution</h4> <p>Spring Framework 5.0 introduced basic support for executing tests in parallel within a
single JVM when using the Spring TestContext Framework. In general, this means that most
test classes or test methods can be run in parallel without any changes to test code
or configuration.</p> <table><thead><tr><th></th> <th>For details on how to set up parallel test execution, see the documentation for your<br>testing framework, build tool, or IDE.</th></tr></thead> <tbody></tbody></table> <p>Keep in mind that the introduction of concurrency into your test suite can result in
unexpected side effects, strange runtime behavior, and tests that fail intermittently or
seemingly randomly. The Spring Team therefore provides the following general guidelines
for when not to run tests in parallel.</p> <p>Do not run tests in parallel if the tests:</p> <ul><li><p>Use Spring Framework’s <code>@DirtiesContext</code> support.</p></li> <li><p>Use Spring Boot’s <code>@MockBean</code> or <code>@SpyBean</code> support.</p></li> <li><p>Use JUnit 4’s <code>@FixMethodOrder</code> support or any testing framework feature
that is designed to ensure that test methods run in a particular order. Note,
however, that this does not apply if entire test classes are run in parallel.</p></li> <li><p>Change the state of shared services or systems such as a database, message broker,
filesystem, and others. This applies to both embedded and external systems.</p></li></ul> <table><thead><tr><th></th> <th>If parallel test execution fails with an exception stating that the <code>ApplicationContext</code>for the current test is no longer active, this typically means that the<code>ApplicationContext</code> was removed from the <code>ContextCache</code> in a different thread.<br><br>This may be due to the use of <code>@DirtiesContext</code> or due to automatic eviction from the<code>ContextCache</code>. If <code>@DirtiesContext</code> is the culprit, you either need to find a way to<br>avoid using <code>@DirtiesContext</code> or exclude such tests from parallel execution. If the<br>maximum size of the <code>ContextCache</code> has been exceeded, you can increase the maximum size<br>of the cache. See the discussion on <a href="#testcontext-ctx-management-caching">context caching</a>for details.</th></tr></thead> <tbody></tbody></table> <table><thead><tr><th></th> <th>Parallel test execution in the Spring TestContext Framework is only possible if<br>the underlying <code>TestContext</code> implementation provides a copy constructor, as explained in<br>the javadoc for <a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/TestContext.html" target="_blank" rel="noopener noreferrer"><code>TestContext</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>. The<code>DefaultTestContext</code> used in Spring provides such a constructor. However, if you use a<br>third-party library that provides a custom <code>TestContext</code> implementation, you need to<br>verify that it is suitable for parallel test execution.</th></tr></thead> <tbody></tbody></table> <h4 id="_3-5-12-testcontext-framework-support-classes"><a href="#_3-5-12-testcontext-framework-support-classes" class="header-anchor">#</a> 3.5.12. TestContext Framework Support Classes</h4> <p>This section describes the various classes that support the Spring TestContext Framework.</p> <h5 id="spring-junit-4-runner"><a href="#spring-junit-4-runner" class="header-anchor">#</a> Spring JUnit 4 Runner</h5> <p>The Spring TestContext Framework offers full integration with JUnit 4 through a custom
runner (supported on JUnit 4.12 or higher). By annotating test classes with<code>@RunWith(SpringJUnit4ClassRunner.class)</code> or the shorter <code>@RunWith(SpringRunner.class)</code>variant, developers can implement standard JUnit 4-based unit and integration tests and
simultaneously reap the benefits of the TestContext framework, such as support for
loading application contexts, dependency injection of test instances, transactional test
method execution, and so on. If you want to use the Spring TestContext Framework with an
alternative runner (such as JUnit 4’s <code>Parameterized</code> runner) or third-party runners
(such as the <code>MockitoJUnitRunner</code>), you can, optionally, use<a href="#testcontext-junit4-rules">Spring’s support for JUnit rules</a> instead.</p> <p>The following code listing shows the minimal requirements for configuring a test class to
run with the custom Spring <code>Runner</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@RunWith(SpringRunner.class)
@TestExecutionListeners({})
public class SimpleTest {

    @Test
    public void testMethod() {
        // test logic...
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@RunWith(SpringRunner::class)
@TestExecutionListeners
class SimpleTest {

    @Test
    fun testMethod() {
        // test logic...
    }
}
</code></pre></div><p>In the preceding example, <code>@TestExecutionListeners</code> is configured with an empty list, to
disable the default listeners, which otherwise would require an <code>ApplicationContext</code> to
be configured through <code>@ContextConfiguration</code>.</p> <h5 id="spring-junit-4-rules"><a href="#spring-junit-4-rules" class="header-anchor">#</a> Spring JUnit 4 Rules</h5> <p>The <code>org.springframework.test.context.junit4.rules</code> package provides the following JUnit
4 rules (supported on JUnit 4.12 or higher):</p> <ul><li><p><code>SpringClassRule</code></p></li> <li><p><code>SpringMethodRule</code></p></li></ul> <p><code>SpringClassRule</code> is a JUnit <code>TestRule</code> that supports class-level features of the Spring
TestContext Framework, whereas <code>SpringMethodRule</code> is a JUnit <code>MethodRule</code> that supports
instance-level and method-level features of the Spring TestContext Framework.</p> <p>In contrast to the <code>SpringRunner</code>, Spring’s rule-based JUnit support has the advantage of
being independent of any <code>org.junit.runner.Runner</code> implementation and can, therefore, be
combined with existing alternative runners (such as JUnit 4’s <code>Parameterized</code>) or
third-party runners (such as the <code>MockitoJUnitRunner</code>).</p> <p>To support the full functionality of the TestContext framework, you must combine a<code>SpringClassRule</code> with a <code>SpringMethodRule</code>. The following example shows the proper way
to declare these rules in an integration test:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// Optionally specify a non-Spring Runner via @RunWith(...)
@ContextConfiguration
public class IntegrationTest {

    @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Test
    public void testMethod() {
        // test logic...
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// Optionally specify a non-Spring Runner via @RunWith(...)
@ContextConfiguration
class IntegrationTest {

    @Rule
    val springMethodRule = SpringMethodRule()

    @Test
    fun testMethod() {
        // test logic...
    }

    companion object {
        @ClassRule
        val springClassRule = SpringClassRule()
    }
}
</code></pre></div><h5 id="junit-4-support-classes"><a href="#junit-4-support-classes" class="header-anchor">#</a> JUnit 4 Support Classes</h5> <p>The <code>org.springframework.test.context.junit4</code> package provides the following support
classes for JUnit 4-based test cases (supported on JUnit 4.12 or higher):</p> <ul><li><p><code>AbstractJUnit4SpringContextTests</code></p></li> <li><p><code>AbstractTransactionalJUnit4SpringContextTests</code></p></li></ul> <p><code>AbstractJUnit4SpringContextTests</code> is an abstract base test class that integrates the
Spring TestContext Framework with explicit <code>ApplicationContext</code> testing support in a
JUnit 4 environment. When you extend <code>AbstractJUnit4SpringContextTests</code>, you can access a<code>protected</code> <code>applicationContext</code> instance variable that you can use to perform explicit
bean lookups or to test the state of the context as a whole.</p> <p><code>AbstractTransactionalJUnit4SpringContextTests</code> is an abstract transactional extension of<code>AbstractJUnit4SpringContextTests</code> that adds some convenience functionality for JDBC
access. This class expects a <code>javax.sql.DataSource</code> bean and a<code>PlatformTransactionManager</code> bean to be defined in the <code>ApplicationContext</code>. When you
extend <code>AbstractTransactionalJUnit4SpringContextTests</code>, you can access a <code>protected``jdbcTemplate</code> instance variable that you can use to run SQL statements to query the
database. You can use such queries to confirm database state both before and after
running database-related application code, and Spring ensures that such queries run in
the scope of the same transaction as the application code. When used in conjunction with
an ORM tool, be sure to avoid <a href="#testcontext-tx-false-positives">false positives</a>.
As mentioned in <a href="#integration-testing-support-jdbc">JDBC Testing Support</a>,<code>AbstractTransactionalJUnit4SpringContextTests</code> also provides convenience methods that
delegate to methods in <code>JdbcTestUtils</code> by using the aforementioned <code>jdbcTemplate</code>.
Furthermore, <code>AbstractTransactionalJUnit4SpringContextTests</code> provides an<code>executeSqlScript(..)</code> method for running SQL scripts against the configured <code>DataSource</code>.</p> <table><thead><tr><th></th> <th>These classes are a convenience for extension. If you do not want your test classes<br>to be tied to a Spring-specific class hierarchy, you can configure your own custom test<br>classes by using <code>@RunWith(SpringRunner.class)</code> or <a href="#testcontext-junit4-rules">Spring’s<br>JUnit rules</a>.</th></tr></thead> <tbody></tbody></table> <h5 id="springextension-for-junit-jupiter"><a href="#springextension-for-junit-jupiter" class="header-anchor">#</a> SpringExtension for JUnit Jupiter</h5> <p>The Spring TestContext Framework offers full integration with the JUnit Jupiter testing
framework, introduced in JUnit 5. By annotating test classes with<code>@ExtendWith(SpringExtension.class)</code>, you can implement standard JUnit Jupiter-based unit
and integration tests and simultaneously reap the benefits of the TestContext framework,
such as support for loading application contexts, dependency injection of test instances,
transactional test method execution, and so on.</p> <p>Furthermore, thanks to the rich extension API in JUnit Jupiter, Spring provides the
following features above and beyond the feature set that Spring supports for JUnit 4 and
TestNG:</p> <ul><li><p>Dependency injection for test constructors, test methods, and test lifecycle callback
methods. See <a href="#testcontext-junit-jupiter-di">Dependency Injection with <code>SpringExtension</code></a> for further details.</p></li> <li><p>Powerful support for <a href="https://junit.org/junit5/docs/current/user-guide/#extensions-conditions" target="_blank" rel="noopener noreferrer">conditional
test execution<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> based on SpEL expressions, environment variables, system properties,
and so on. See the documentation for <code>@EnabledIf</code> and <code>@DisabledIf</code> in<a href="#integration-testing-annotations-junit-jupiter">Spring JUnit Jupiter Testing Annotations</a> for further details and examples.</p></li> <li><p>Custom composed annotations that combine annotations from Spring and JUnit Jupiter. See
the <code>@TransactionalDevTestConfig</code> and <code>@TransactionalIntegrationTest</code> examples in<a href="#integration-testing-annotations-meta">Meta-Annotation Support for Testing</a> for further details.</p></li></ul> <p>The following code listing shows how to configure a test class to use the<code>SpringExtension</code> in conjunction with <code>@ContextConfiguration</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// Instructs JUnit Jupiter to extend the test with Spring support.
@ExtendWith(SpringExtension.class)
// Instructs Spring to load an ApplicationContext from TestConfig.class
@ContextConfiguration(classes = TestConfig.class)
class SimpleTests {

    @Test
    void testMethod() {
        // test logic...
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// Instructs JUnit Jupiter to extend the test with Spring support.
@ExtendWith(SpringExtension::class)
// Instructs Spring to load an ApplicationContext from TestConfig::class
@ContextConfiguration(classes = [TestConfig::class])
class SimpleTests {

    @Test
    fun testMethod() {
        // test logic...
    }
}
</code></pre></div><p>Since you can also use annotations in JUnit 5 as meta-annotations, Spring provides the<code>@SpringJUnitConfig</code> and <code>@SpringJUnitWebConfig</code> composed annotations to simplify the
configuration of the test <code>ApplicationContext</code> and JUnit Jupiter.</p> <p>The following example uses <code>@SpringJUnitConfig</code> to reduce the amount of configuration
used in the previous example:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// Instructs Spring to register the SpringExtension with JUnit
// Jupiter and load an ApplicationContext from TestConfig.class
@SpringJUnitConfig(TestConfig.class)
class SimpleTests {

    @Test
    void testMethod() {
        // test logic...
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// Instructs Spring to register the SpringExtension with JUnit
// Jupiter and load an ApplicationContext from TestConfig.class
@SpringJUnitConfig(TestConfig::class)
class SimpleTests {

    @Test
    fun testMethod() {
        // test logic...
    }
}
</code></pre></div><p>Similarly, the following example uses <code>@SpringJUnitWebConfig</code> to create a<code>WebApplicationContext</code> for use with JUnit Jupiter:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// Instructs Spring to register the SpringExtension with JUnit
// Jupiter and load a WebApplicationContext from TestWebConfig.class
@SpringJUnitWebConfig(TestWebConfig.class)
class SimpleWebTests {

    @Test
    void testMethod() {
        // test logic...
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// Instructs Spring to register the SpringExtension with JUnit
// Jupiter and load a WebApplicationContext from TestWebConfig::class
@SpringJUnitWebConfig(TestWebConfig::class)
class SimpleWebTests {

    @Test
    fun testMethod() {
        // test logic...
    }
}
</code></pre></div><p>See the documentation for <code>@SpringJUnitConfig</code> and <code>@SpringJUnitWebConfig</code> in<a href="#integration-testing-annotations-junit-jupiter">Spring JUnit Jupiter Testing Annotations</a> for further details.</p> <h5 id="dependency-injection-with-springextension"><a href="#dependency-injection-with-springextension" class="header-anchor">#</a> Dependency Injection with <code>SpringExtension</code></h5> <p><code>SpringExtension</code> implements the<a href="https://junit.org/junit5/docs/current/user-guide/#extensions-parameter-resolution" target="_blank" rel="noopener noreferrer"><code>ParameterResolver</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>extension API from JUnit Jupiter, which lets Spring provide dependency injection for test
constructors, test methods, and test lifecycle callback methods.</p> <p>Specifically, <code>SpringExtension</code> can inject dependencies from the test’s<code>ApplicationContext</code> into test constructors and methods that are annotated with<code>@BeforeAll</code>, <code>@AfterAll</code>, <code>@BeforeEach</code>, <code>@AfterEach</code>, <code>@Test</code>, <code>@RepeatedTest</code>,<code>@ParameterizedTest</code>, and others.</p> <h6 id="constructor-injection"><a href="#constructor-injection" class="header-anchor">#</a> Constructor Injection</h6> <p>If a specific parameter in a constructor for a JUnit Jupiter test class is of type<code>ApplicationContext</code> (or a sub-type thereof) or is annotated or meta-annotated with<code>@Autowired</code>, <code>@Qualifier</code>, or <code>@Value</code>, Spring injects the value for that specific
parameter with the corresponding bean or value from the test’s <code>ApplicationContext</code>.</p> <p>Spring can also be configured to autowire all arguments for a test class constructor if
the constructor is considered to be <em>autowirable</em>. A constructor is considered to be
autowirable if one of the following conditions is met (in order of precedence).</p> <ul><li><p>The constructor is annotated with <code>@Autowired</code>.</p></li> <li><p><code>@TestConstructor</code> is present or meta-present on the test class with the <code>autowireMode</code>attribute set to <code>ALL</code>.</p></li> <li><p>The default <em>test constructor autowire mode</em> has been changed to <code>ALL</code>.</p></li></ul> <p>See <a href="#integration-testing-annotations-testconstructor"><code>@TestConstructor</code></a> for details on the use of<code>@TestConstructor</code> and how to change the global <em>test constructor autowire mode</em>.</p> <table><thead><tr><th></th> <th>If the constructor for a test class is considered to be <em>autowirable</em>, Spring<br>assumes the responsibility for resolving arguments for all parameters in the constructor.<br>Consequently, no other <code>ParameterResolver</code> registered with JUnit Jupiter can resolve<br>parameters for such a constructor.</th></tr></thead> <tbody></tbody></table> <table><thead><tr><th></th> <th>Constructor injection for test classes must not be used in conjunction with JUnit<br>Jupiter’s <code>@TestInstance(PER_CLASS)</code> support if <code>@DirtiesContext</code> is used to close the<br>test’s <code>ApplicationContext</code> before or after test methods.<br><br>The reason is that <code>@TestInstance(PER_CLASS)</code> instructs JUnit Jupiter to cache the test<br>instance between test method invocations. Consequently, the test instance will retain<br>references to beans that were originally injected from an <code>ApplicationContext</code> that has<br>been subsequently closed. Since the constructor for the test class will only be invoked<br>once in such scenarios, dependency injection will not occur again, and subsequent tests<br>will interact with beans from the closed <code>ApplicationContext</code> which may result in errors.<br><br>To use <code>@DirtiesContext</code> with &quot;before test method&quot; or &quot;after test method&quot; modes in<br>conjunction with <code>@TestInstance(PER_CLASS)</code>, one must configure dependencies from Spring<br>to be supplied via field or setter injection so that they can be re-injected between test<br>method invocations.</th></tr></thead> <tbody></tbody></table> <p>In the following example, Spring injects the <code>OrderService</code> bean from the<code>ApplicationContext</code> loaded from <code>TestConfig.class</code> into the<code>OrderServiceIntegrationTests</code> constructor.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig.class)
class OrderServiceIntegrationTests {

    private final OrderService orderService;

    @Autowired
    OrderServiceIntegrationTests(OrderService orderService) {
        this.orderService = orderService;
    }

    // tests that use the injected OrderService
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig::class)
class OrderServiceIntegrationTests @Autowired constructor(private val orderService: OrderService){
    // tests that use the injected OrderService
}
</code></pre></div><p>Note that this feature lets test dependencies be <code>final</code> and therefore immutable.</p> <p>If the <code>spring.test.constructor.autowire.mode</code> property is to <code>all</code> (see<a href="#integration-testing-annotations-testconstructor"><code>@TestConstructor</code></a>), we can omit the declaration of<code>@Autowired</code> on the constructor in the previous example, resulting in the following.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig.class)
class OrderServiceIntegrationTests {

    private final OrderService orderService;

    OrderServiceIntegrationTests(OrderService orderService) {
        this.orderService = orderService;
    }

    // tests that use the injected OrderService
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig::class)
class OrderServiceIntegrationTests(val orderService:OrderService) {
    // tests that use the injected OrderService
}
</code></pre></div><h6 id="method-injection"><a href="#method-injection" class="header-anchor">#</a> Method Injection</h6> <p>If a parameter in a JUnit Jupiter test method or test lifecycle callback method is of
type <code>ApplicationContext</code> (or a sub-type thereof) or is annotated or meta-annotated with<code>@Autowired</code>, <code>@Qualifier</code>, or <code>@Value</code>, Spring injects the value for that specific
parameter with the corresponding bean from the test’s <code>ApplicationContext</code>.</p> <p>In the following example, Spring injects the <code>OrderService</code> from the <code>ApplicationContext</code>loaded from <code>TestConfig.class</code> into the <code>deleteOrder()</code> test method:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig.class)
class OrderServiceIntegrationTests {

    @Test
    void deleteOrder(@Autowired OrderService orderService) {
        // use orderService from the test's ApplicationContext
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig::class)
class OrderServiceIntegrationTests {

    @Test
    fun deleteOrder(@Autowired orderService: OrderService) {
        // use orderService from the test's ApplicationContext
    }
}
</code></pre></div><p>Due to the robustness of the <code>ParameterResolver</code> support in JUnit Jupiter, you can also
have multiple dependencies injected into a single method, not only from Spring but also
from JUnit Jupiter itself or other third-party extensions.</p> <p>The following example shows how to have both Spring and JUnit Jupiter inject dependencies
into the <code>placeOrderRepeatedly()</code> test method simultaneously.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig.class)
class OrderServiceIntegrationTests {

    @RepeatedTest(10)
    void placeOrderRepeatedly(RepetitionInfo repetitionInfo,
            @Autowired OrderService orderService) {

        // use orderService from the test's ApplicationContext
        // and repetitionInfo from JUnit Jupiter
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig::class)
class OrderServiceIntegrationTests {

    @RepeatedTest(10)
    fun placeOrderRepeatedly(repetitionInfo:RepetitionInfo, @Autowired orderService:OrderService) {

        // use orderService from the test's ApplicationContext
        // and repetitionInfo from JUnit Jupiter
    }
}
</code></pre></div><p>Note that the use of <code>@RepeatedTest</code> from JUnit Jupiter lets the test method gain access
to the <code>RepetitionInfo</code>.</p> <h5 id="nested-test-class-configuration"><a href="#nested-test-class-configuration" class="header-anchor">#</a> <code>@Nested</code> test class configuration</h5> <p>The <em>Spring TestContext Framework</em> has supported the use of test-related annotations on<code>@Nested</code> test classes in JUnit Jupiter since Spring Framework 5.0; however, until Spring
Framework 5.3 class-level test configuration annotations were not <em>inherited</em> from
enclosing classes like they are from superclasses.</p> <p>Spring Framework 5.3 introduces first-class support for inheriting test class
configuration from enclosing classes, and such configuration will be inherited by
default. To change from the default <code>INHERIT</code> mode to <code>OVERRIDE</code> mode, you may annotate
an individual <code>@Nested</code> test class with<code>@NestedTestConfiguration(EnclosingConfiguration.OVERRIDE)</code>. An explicit<code>@NestedTestConfiguration</code> declaration will apply to the annotated test class as well as
any of its subclasses and nested classes. Thus, you may annotate a top-level test class
with <code>@NestedTestConfiguration</code>, and that will apply to all of its nested test classes
recursively.</p> <p>In order to allow development teams to change the default to <code>OVERRIDE</code> – for example,
for compatibility with Spring Framework 5.0 through 5.2 – the default mode can be changed
globally via a JVM system property or a <code>spring.properties</code> file in the root of the
classpath. See the <a href="#integration-testing-annotations-nestedtestconfiguration">&quot;Changing
the default enclosing configuration inheritance mode&quot;</a> note for details.</p> <p>Although the following &quot;Hello World&quot; example is very simplistic, it shows how to declare
common configuration on a top-level class that is inherited by its <code>@Nested</code> test
classes. In this particular example, only the <code>TestConfig</code> configuration class is
inherited. Each nested test class provides its own set of active profiles, resulting in a
distinct <code>ApplicationContext</code> for each nested test class (see<a href="#testcontext-ctx-management-caching">Context Caching</a> for details). Consult the list of<a href="#integration-testing-annotations-nestedtestconfiguration">supported annotations</a> to see
which annotations can be inherited in <code>@Nested</code> test classes.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig.class)
class GreetingServiceTests {

    @Nested
    @ActiveProfiles(&quot;lang_en&quot;)
    class EnglishGreetings {

        @Test
        void hello(@Autowired GreetingService service) {
            assertThat(service.greetWorld()).isEqualTo(&quot;Hello World&quot;);
        }
    }

    @Nested
    @ActiveProfiles(&quot;lang_de&quot;)
    class GermanGreetings {

        @Test
        void hello(@Autowired GreetingService service) {
            assertThat(service.greetWorld()).isEqualTo(&quot;Hallo Welt&quot;);
        }
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(TestConfig::class)
class GreetingServiceTests {

    @Nested
    @ActiveProfiles(&quot;lang_en&quot;)
    inner class EnglishGreetings {

        @Test
        fun hello(@Autowired service:GreetingService) {
            assertThat(service.greetWorld()).isEqualTo(&quot;Hello World&quot;)
        }
    }

    @Nested
    @ActiveProfiles(&quot;lang_de&quot;)
    inner class GermanGreetings {

        @Test
        fun hello(@Autowired service:GreetingService) {
            assertThat(service.greetWorld()).isEqualTo(&quot;Hallo Welt&quot;)
        }
    }
}
</code></pre></div><h5 id="testng-support-classes"><a href="#testng-support-classes" class="header-anchor">#</a> TestNG Support Classes</h5> <p>The <code>org.springframework.test.context.testng</code> package provides the following support
classes for TestNG based test cases:</p> <ul><li><p><code>AbstractTestNGSpringContextTests</code></p></li> <li><p><code>AbstractTransactionalTestNGSpringContextTests</code></p></li></ul> <p><code>AbstractTestNGSpringContextTests</code> is an abstract base test class that integrates the
Spring TestContext Framework with explicit <code>ApplicationContext</code> testing support in a
TestNG environment. When you extend <code>AbstractTestNGSpringContextTests</code>, you can access a<code>protected</code> <code>applicationContext</code> instance variable that you can use to perform explicit
bean lookups or to test the state of the context as a whole.</p> <p><code>AbstractTransactionalTestNGSpringContextTests</code> is an abstract transactional extension of<code>AbstractTestNGSpringContextTests</code> that adds some convenience functionality for JDBC
access. This class expects a <code>javax.sql.DataSource</code> bean and a<code>PlatformTransactionManager</code> bean to be defined in the <code>ApplicationContext</code>. When you
extend <code>AbstractTransactionalTestNGSpringContextTests</code>, you can access a <code>protected``jdbcTemplate</code> instance variable that you can use to run SQL statements to query the
database. You can use such queries to confirm database state both before and after
running database-related application code, and Spring ensures that such queries run in
the scope of the same transaction as the application code. When used in conjunction with
an ORM tool, be sure to avoid <a href="#testcontext-tx-false-positives">false positives</a>.
As mentioned in <a href="#integration-testing-support-jdbc">JDBC Testing Support</a>,<code>AbstractTransactionalTestNGSpringContextTests</code> also provides convenience methods that
delegate to methods in <code>JdbcTestUtils</code> by using the aforementioned <code>jdbcTemplate</code>.
Furthermore, <code>AbstractTransactionalTestNGSpringContextTests</code> provides an<code>executeSqlScript(..)</code> method for running SQL scripts against the configured <code>DataSource</code>.</p> <table><thead><tr><th></th> <th>These classes are a convenience for extension. If you do not want your test classes<br>to be tied to a Spring-specific class hierarchy, you can configure your own custom test<br>classes by using <code>@ContextConfiguration</code>, <code>@TestExecutionListeners</code>, and so on and by<br>manually instrumenting your test class with a <code>TestContextManager</code>. See the source code<br>of <code>AbstractTestNGSpringContextTests</code> for an example of how to instrument your test class.</th></tr></thead> <tbody></tbody></table> <h3 id="_3-6-webtestclient"><a href="#_3-6-webtestclient" class="header-anchor">#</a> 3.6. WebTestClient</h3> <p><code>WebTestClient</code> is an HTTP client designed for testing server applications. It wraps
Spring’s <a href="/en/spring-framework/web-reactive.html#webflux-client">WebClient</a> and uses it to perform requests
but exposes a testing facade for verifying responses. <code>WebTestClient</code> can be used to
perform end-to-end HTTP tests. It can also be used to test Spring MVC and Spring WebFlux
applications without a running server via mock server request and response objects.</p> <table><thead><tr><th></th> <th>Kotlin users: See <a href="/en/spring-framework/languages.html#kotlin-webtestclient-issue">this section</a>related to use of the <code>WebTestClient</code>.</th></tr></thead> <tbody></tbody></table> <h4 id="_3-6-1-setup"><a href="#_3-6-1-setup" class="header-anchor">#</a> 3.6.1. Setup</h4> <p>To set up a <code>WebTestClient</code> you need to choose a server setup to bind to. This can be one
of several mock server setup choices or a connection to a live server.</p> <h5 id="bind-to-controller"><a href="#bind-to-controller" class="header-anchor">#</a> Bind to Controller</h5> <p>This setup allows you to test specific controller(s) via mock request and response objects,
without a running server.</p> <p>For WebFlux applications, use the following which loads infrastructure equivalent to the<a href="/en/spring-framework/web-reactive.html#webflux-config">WebFlux Java config</a>, registers the given
controller(s), and creates a <a href="/en/spring-framework/web-reactive.html#webflux-web-handler-api">WebHandler chain</a>to handle requests:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>WebTestClient client =
        WebTestClient.bindToController(new TestController()).build();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val client = WebTestClient.bindToController(TestController()).build()
</code></pre></div><p>For Spring MVC, use the following which delegates to the<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilder.html" target="_blank" rel="noopener noreferrer">StandaloneMockMvcBuilder<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>to load infrastructure equivalent to the <a href="/en/spring-framework/web.html#mvc-config">WebMvc Java config</a>,
registers the given controller(s), and creates an instance of<a href="#spring-mvc-test-framework">MockMvc</a> to handle requests:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>WebTestClient client =
        MockMvcWebTestClient.bindToController(new TestController()).build();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val client = MockMvcWebTestClient.bindToController(TestController()).build()
</code></pre></div><h5 id="bind-to-applicationcontext"><a href="#bind-to-applicationcontext" class="header-anchor">#</a> Bind to <code>ApplicationContext</code></h5> <p>This setup allows you to load Spring configuration with Spring MVC or Spring WebFlux
infrastructure and controller declarations and use it to handle requests via mock request
and response objects, without a running server.</p> <p>For WebFlux, use the following where the Spring <code>ApplicationContext</code> is passed to<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/server/adapter/WebHttpHandlerBuilder.html#applicationContext-org.springframework.context.ApplicationContext-" target="_blank" rel="noopener noreferrer">WebHttpHandlerBuilder<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>to create the <a href="/en/spring-framework/web-reactive.html#webflux-web-handler-api">WebHandler chain</a> to handle
requests:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(WebConfig.class) (1)
class MyTests {

    WebTestClient client;

    @BeforeEach
    void setUp(ApplicationContext context) {  (2)
        client = WebTestClient.bindToApplicationContext(context).build(); (3)
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specify the configuration to load</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Inject the configuration</td></tr> <tr><td><strong>3</strong></td> <td>Create the <code>WebTestClient</code></td></tr></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitConfig(WebConfig::class) (1)
class MyTests {

    lateinit var client: WebTestClient

    @BeforeEach
    fun setUp(context: ApplicationContext) { (2)
        client = WebTestClient.bindToApplicationContext(context).build() (3)
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specify the configuration to load</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Inject the configuration</td></tr> <tr><td><strong>3</strong></td> <td>Create the <code>WebTestClient</code></td></tr></tbody></table> <p>For Spring MVC, use the following where the Spring <code>ApplicationContext</code> is passed to<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/web/servlet/setup/MockMvcBuilders.html#webAppContextSetup-org.springframework.web.context.WebApplicationContext-" target="_blank" rel="noopener noreferrer">MockMvcBuilders.webAppContextSetup<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>to create a <a href="#spring-mvc-test-framework">MockMvc</a> instance to handle
requests:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
@WebAppConfiguration(&quot;classpath:META-INF/web-resources&quot;) (1)
@ContextHierarchy({
    @ContextConfiguration(classes = RootConfig.class),
    @ContextConfiguration(classes = WebConfig.class)
})
class MyTests {

    @Autowired
    WebApplicationContext wac; (2)

    WebTestClient client;

    @BeforeEach
    void setUp() {
        client = MockMvcWebTestClient.bindToApplicationContext(this.wac).build(); (3)
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specify the configuration to load</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Inject the configuration</td></tr> <tr><td><strong>3</strong></td> <td>Create the <code>WebTestClient</code></td></tr></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@ExtendWith(SpringExtension.class)
@WebAppConfiguration(&quot;classpath:META-INF/web-resources&quot;) (1)
@ContextHierarchy({
    @ContextConfiguration(classes = RootConfig.class),
    @ContextConfiguration(classes = WebConfig.class)
})
class MyTests {

    @Autowired
    lateinit var wac: WebApplicationContext; (2)

    lateinit var client: WebTestClient

    @BeforeEach
    fun setUp() { (2)
        client = MockMvcWebTestClient.bindToApplicationContext(wac).build() (3)
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Specify the configuration to load</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Inject the configuration</td></tr> <tr><td><strong>3</strong></td> <td>Create the <code>WebTestClient</code></td></tr></tbody></table> <h5 id="bind-to-router-function"><a href="#bind-to-router-function" class="header-anchor">#</a> Bind to Router Function</h5> <p>This setup allows you to test <a href="/en/spring-framework/web-reactive.html#webflux-fn">functional endpoints</a> via
mock request and response objects, without a running server.</p> <p>For WebFlux, use the following which delegates to <code>RouterFunctions.toWebHandler</code> to
create a server setup to handle requests:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>RouterFunction&lt;?&gt; route = ...
client = WebTestClient.bindToRouterFunction(route).build();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val route: RouterFunction&lt;*&gt; = ...
val client = WebTestClient.bindToRouterFunction(route).build()
</code></pre></div><p>For Spring MVC there are currently no options to test<a href="/en/spring-framework/web.html#webmvc-fn">WebMvc functional endpoints</a>.</p> <h5 id="bind-to-server"><a href="#bind-to-server" class="header-anchor">#</a> Bind to Server</h5> <p>This setup connects to a running server to perform full, end-to-end HTTP tests:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>client = WebTestClient.bindToServer().baseUrl(&quot;http://localhost:8080&quot;).build();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>client = WebTestClient.bindToServer().baseUrl(&quot;http://localhost:8080&quot;).build()
</code></pre></div><h5 id="client-config"><a href="#client-config" class="header-anchor">#</a> Client Config</h5> <p>In addition to the server setup options described earlier, you can also configure client
options, including base URL, default headers, client filters, and others. These options
are readily available following <code>bindToServer()</code>. For all other configuration options,
you need to use <code>configureClient()</code> to transition from server to client configuration, as
follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>client = WebTestClient.bindToController(new TestController())
        .configureClient()
        .baseUrl(&quot;/test&quot;)
        .build();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>client = WebTestClient.bindToController(TestController())
        .configureClient()
        .baseUrl(&quot;/test&quot;)
        .build()
</code></pre></div><h4 id="_3-6-2-writing-tests"><a href="#_3-6-2-writing-tests" class="header-anchor">#</a> 3.6.2. Writing Tests</h4> <p><code>WebTestClient</code> provides an API identical to <a href="/en/spring-framework/web-reactive.html#webflux-client">WebClient</a>up to the point of performing a request by using <code>exchange()</code>. See the<a href="/en/spring-framework/web-reactive.html#webflux-client-body">WebClient</a> documentation for examples on how to
prepare a request with any content including form data, multipart data, and more.</p> <p>After the call to <code>exchange()</code>, <code>WebTestClient</code> diverges from the <code>WebClient</code> and
instead continues with a workflow to verify responses.</p> <p>To assert the response status and headers, use the following:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>client.get().uri(&quot;/persons/1&quot;)
    .accept(MediaType.APPLICATION_JSON)
    .exchange()
    .expectStatus().isOk()
    .expectHeader().contentType(MediaType.APPLICATION_JSON);
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>client.get().uri(&quot;/persons/1&quot;)
    .accept(MediaType.APPLICATION_JSON)
    .exchange()
    .expectStatus().isOk()
    .expectHeader().contentType(MediaType.APPLICATION_JSON)
</code></pre></div><p>If you would like for all expectations to be asserted even if one of them fails, you can
use <code>expectAll(..)</code> instead of multiple chained <code>expect*(..)</code> calls. This feature is
similar to the <em>soft assertions</em> support in AssertJ and the <code>assertAll()</code> support in
JUnit Jupiter.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>client.get().uri(&quot;/persons/1&quot;)
    .accept(MediaType.APPLICATION_JSON)
    .exchange()
    .expectAll(
        spec -&gt; spec.expectStatus().isOk(),
        spec -&gt; spec.expectHeader().contentType(MediaType.APPLICATION_JSON)
    );
</code></pre></div><p>You can then choose to decode the response body through one of the following:</p> <ul><li><p><code>expectBody(Class&lt;T&gt;)</code>: Decode to single object.</p></li> <li><p><code>expectBodyList(Class&lt;T&gt;)</code>: Decode and collect objects to <code>List&lt;T&gt;</code>.</p></li> <li><p><code>expectBody()</code>: Decode to <code>byte[]</code> for <a href="#webtestclient-json">JSON Content</a> or an empty body.</p></li></ul> <p>And perform assertions on the resulting higher level Object(s):</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>client.get().uri(&quot;/persons&quot;)
        .exchange()
        .expectStatus().isOk()
        .expectBodyList(Person.class).hasSize(3).contains(person);
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>import org.springframework.test.web.reactive.server.expectBodyList

client.get().uri(&quot;/persons&quot;)
        .exchange()
        .expectStatus().isOk()
        .expectBodyList&lt;Person&gt;().hasSize(3).contains(person)
</code></pre></div><p>If the built-in assertions are insufficient, you can consume the object instead and
perform any other assertions:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>import org.springframework.test.web.reactive.server.expectBody

client.get().uri(&quot;/persons/1&quot;)
        .exchange()
        .expectStatus().isOk()
        .expectBody(Person.class)
        .consumeWith(result -&gt; {
            // custom assertions (e.g. AssertJ)...
        });
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>client.get().uri(&quot;/persons/1&quot;)
        .exchange()
        .expectStatus().isOk()
        .expectBody&lt;Person&gt;()
        .consumeWith {
            // custom assertions (e.g. AssertJ)...
        }
</code></pre></div><p>Or you can exit the workflow and obtain an <code>EntityExchangeResult</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>EntityExchangeResult&lt;Person&gt; result = client.get().uri(&quot;/persons/1&quot;)
        .exchange()
        .expectStatus().isOk()
        .expectBody(Person.class)
        .returnResult();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>import org.springframework.test.web.reactive.server.expectBody

val result = client.get().uri(&quot;/persons/1&quot;)
        .exchange()
        .expectStatus().isOk
        .expectBody&lt;Person&gt;()
        .returnResult()
</code></pre></div><table><thead><tr><th></th> <th>When you need to decode to a target type with generics, look for the overloaded methods<br>that accept<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/core/ParameterizedTypeReference.html" target="_blank" rel="noopener noreferrer"><code>ParameterizedTypeReference</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>instead of <code>Class&lt;T&gt;</code>.</th></tr></thead> <tbody></tbody></table> <h5 id="no-content"><a href="#no-content" class="header-anchor">#</a> No Content</h5> <p>If the response is not expected to have content, you can assert that as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>client.post().uri(&quot;/persons&quot;)
        .body(personMono, Person.class)
        .exchange()
        .expectStatus().isCreated()
        .expectBody().isEmpty();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>client.post().uri(&quot;/persons&quot;)
        .bodyValue(person)
        .exchange()
        .expectStatus().isCreated()
        .expectBody().isEmpty()
</code></pre></div><p>If you want to ignore the response content, the following releases the content without
any assertions:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>client.get().uri(&quot;/persons/123&quot;)
        .exchange()
        .expectStatus().isNotFound()
        .expectBody(Void.class);
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>client.get().uri(&quot;/persons/123&quot;)
        .exchange()
        .expectStatus().isNotFound
        .expectBody&lt;Unit&gt;()
</code></pre></div><h5 id="json-content"><a href="#json-content" class="header-anchor">#</a> JSON Content</h5> <p>You can use <code>expectBody()</code> without a target type to perform assertions on the raw
content rather than through higher level Object(s).</p> <p>To verify the full JSON content with <a href="https://jsonassert.skyscreamer.org" target="_blank" rel="noopener noreferrer">JSONAssert<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>client.get().uri(&quot;/persons/1&quot;)
        .exchange()
        .expectStatus().isOk()
        .expectBody()
        .json(&quot;{\&quot;name\&quot;:\&quot;Jane\&quot;}&quot;)
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>client.get().uri(&quot;/persons/1&quot;)
        .exchange()
        .expectStatus().isOk()
        .expectBody()
        .json(&quot;{\&quot;name\&quot;:\&quot;Jane\&quot;}&quot;)
</code></pre></div><p>To verify JSON content with <a href="https://github.com/jayway/JsonPath" target="_blank" rel="noopener noreferrer">JSONPath<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>client.get().uri(&quot;/persons&quot;)
        .exchange()
        .expectStatus().isOk()
        .expectBody()
        .jsonPath(&quot;$[0].name&quot;).isEqualTo(&quot;Jane&quot;)
        .jsonPath(&quot;$[1].name&quot;).isEqualTo(&quot;Jason&quot;);
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>client.get().uri(&quot;/persons&quot;)
        .exchange()
        .expectStatus().isOk()
        .expectBody()
        .jsonPath(&quot;$[0].name&quot;).isEqualTo(&quot;Jane&quot;)
        .jsonPath(&quot;$[1].name&quot;).isEqualTo(&quot;Jason&quot;)
</code></pre></div><h5 id="streaming-responses"><a href="#streaming-responses" class="header-anchor">#</a> Streaming Responses</h5> <p>To test potentially infinite streams such as <code>&quot;text/event-stream&quot;</code> or<code>&quot;application/x-ndjson&quot;</code>, start by verifying the response status and headers, and then
obtain a <code>FluxExchangeResult</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>FluxExchangeResult&lt;MyEvent&gt; result = client.get().uri(&quot;/events&quot;)
        .accept(TEXT_EVENT_STREAM)
        .exchange()
        .expectStatus().isOk()
        .returnResult(MyEvent.class);
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>import org.springframework.test.web.reactive.server.returnResult

val result = client.get().uri(&quot;/events&quot;)
        .accept(TEXT_EVENT_STREAM)
        .exchange()
        .expectStatus().isOk()
        .returnResult&lt;MyEvent&gt;()
</code></pre></div><p>Now you’re ready to consume the response stream with <code>StepVerifier</code> from <code>reactor-test</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>Flux&lt;Event&gt; eventFlux = result.getResponseBody();

StepVerifier.create(eventFlux)
        .expectNext(person)
        .expectNextCount(4)
        .consumeNextWith(p -&gt; ...)
        .thenCancel()
        .verify();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val eventFlux = result.getResponseBody()

StepVerifier.create(eventFlux)
        .expectNext(person)
        .expectNextCount(4)
        .consumeNextWith { p -&gt; ... }
        .thenCancel()
        .verify()
</code></pre></div><h5 id="mockmvc-assertions"><a href="#mockmvc-assertions" class="header-anchor">#</a> MockMvc Assertions</h5> <p><code>WebTestClient</code> is an HTTP client and as such it can only verify what is in the client
response including status, headers, and body.</p> <p>When testing a Spring MVC application with a MockMvc server setup, you have the extra
choice to perform further assertions on the server response. To do that start by
obtaining an <code>ExchangeResult</code> after asserting the body:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// For a response with a body
EntityExchangeResult&lt;Person&gt; result = client.get().uri(&quot;/persons/1&quot;)
        .exchange()
        .expectStatus().isOk()
        .expectBody(Person.class)
        .returnResult();

// For a response without a body
EntityExchangeResult&lt;Void&gt; result = client.get().uri(&quot;/path&quot;)
        .exchange()
        .expectBody().isEmpty();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// For a response with a body
val result = client.get().uri(&quot;/persons/1&quot;)
        .exchange()
        .expectStatus().isOk()
        .expectBody(Person.class)
        .returnResult();

// For a response without a body
val result = client.get().uri(&quot;/path&quot;)
        .exchange()
        .expectBody().isEmpty();
</code></pre></div><p>Then switch to MockMvc server response assertions:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>MockMvcWebTestClient.resultActionsFor(result)
        .andExpect(model().attribute(&quot;integer&quot;, 3))
        .andExpect(model().attribute(&quot;string&quot;, &quot;a string value&quot;));
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>MockMvcWebTestClient.resultActionsFor(result)
        .andExpect(model().attribute(&quot;integer&quot;, 3))
        .andExpect(model().attribute(&quot;string&quot;, &quot;a string value&quot;));
</code></pre></div><h3 id="_3-7-mockmvc"><a href="#_3-7-mockmvc" class="header-anchor">#</a> 3.7. MockMvc</h3> <p>The Spring MVC Test framework, also known as MockMvc, provides support for testing Spring
MVC applications. It performs full Spring MVC request handling but via mock request and
response objects instead of a running server.</p> <p>MockMvc can be used on its own to perform requests and verify responses. It can also be
used through the <a href="#webtestclient">WebTestClient</a> where MockMvc is plugged in as the server to handle
requests with. The advantage of <code>WebTestClient</code> is the option to work with higher level
objects instead of raw data as well as the ability to switch to full, end-to-end HTTP
tests against a live server and use the same test API.</p> <h4 id="_3-7-1-overview"><a href="#_3-7-1-overview" class="header-anchor">#</a> 3.7.1. Overview</h4> <p>You can write plain unit tests for Spring MVC by instantiating a controller, injecting it
with dependencies, and calling its methods. However such tests do not verify request
mappings, data binding, message conversion, type conversion, validation, and nor
do they involve any of the supporting <code>@InitBinder</code>, <code>@ModelAttribute</code>, or<code>@ExceptionHandler</code> methods.</p> <p>The Spring MVC Test framework, also known as <code>MockMvc</code>, aims to provide more complete
testing for Spring MVC controllers without a running server. It does that by invoking
the <code>DispacherServlet</code> and passing<a href="#mock-objects-servlet">“mock” implementations of the Servlet API</a> from the<code>spring-test</code> module which replicates the full Spring MVC request handling without
a running server.</p> <p>MockMvc is a server side test framework that lets you verify most of the functionality
of a Spring MVC application using lightweight and targeted tests. You can use it on
its own to perform requests and to verify responses, or you can also use it through
the <a href="#webtestclient">WebTestClient</a> API with MockMvc plugged in as the server to handle requests
with.</p> <h5 id="static-imports"><a href="#static-imports" class="header-anchor">#</a> Static Imports</h5> <p>When using MockMvc directly to perform requests, you’ll need static imports for:</p> <ul><li><p><code>MockMvcBuilders.*</code></p></li> <li><p><code>MockMvcRequestBuilders.*</code></p></li> <li><p><code>MockMvcResultMatchers.*</code></p></li> <li><p><code>MockMvcResultHandlers.*</code></p></li></ul> <p>An easy way to remember that is search for <code>MockMvc*</code>. If using Eclipse be sure to also
add the above as “favorite static members” in the Eclipse preferences.</p> <p>When using MockMvc through the <a href="#webtestclient">WebTestClient</a> you do not need static imports.
The <code>WebTestClient</code> provides a fluent API without static imports.</p> <h5 id="setup-choices"><a href="#setup-choices" class="header-anchor">#</a> Setup Choices</h5> <p>MockMvc can be setup in one of two ways. One is to point directly to the controllers you
want to test and programmatically configure Spring MVC infrastructure. The second is to
point to Spring configuration with Spring MVC and controller infrastructure in it.</p> <p>To set up MockMvc for testing a specific controller, use the following:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>class MyWebTests {

    MockMvc mockMvc;

    @BeforeEach
    void setup() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();
    }

    // ...

}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>class MyWebTests {

    lateinit var mockMvc : MockMvc

    @BeforeEach
    fun setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(AccountController()).build()
    }

    // ...

}
</code></pre></div><p>Or you can also use this setup when testing through the<a href="#webtestclient-controller-config">WebTestClient</a> which delegates to the same builder
as shown above.</p> <p>To set up MockMvc through Spring configuration, use the following:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig(locations = &quot;my-servlet-context.xml&quot;)
class MyWebTests {

    MockMvc mockMvc;

    @BeforeEach
    void setup(WebApplicationContext wac) {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    // ...

}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig(locations = [&quot;my-servlet-context.xml&quot;])
class MyWebTests {

    lateinit var mockMvc: MockMvc

    @BeforeEach
    fun setup(wac: WebApplicationContext) {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build()
    }

    // ...

}
</code></pre></div><p>Or you can also use this setup when testing through the<a href="#webtestclient-context-config">WebTestClient</a> which delegates to the same builder
as shown above.</p> <p>Which setup option should you use?</p> <p>The <code>webAppContextSetup</code> loads your actual Spring MVC configuration, resulting in a more
complete integration test. Since the TestContext framework caches the loaded Spring
configuration, it helps keep tests running fast, even as you introduce more tests in your
test suite. Furthermore, you can inject mock services into controllers through Spring
configuration to remain focused on testing the web layer. The following example declares
a mock service with Mockito:</p> <div class="language- extra-class"><pre class="language-text"><code>&lt;bean id=&quot;accountService&quot; class=&quot;org.mockito.Mockito&quot; factory-method=&quot;mock&quot;&gt;
    &lt;constructor-arg value=&quot;org.example.AccountService&quot;/&gt;
&lt;/bean&gt;
</code></pre></div><p>You can then inject the mock service into the test to set up and verify your
expectations, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig(locations = &quot;test-servlet-context.xml&quot;)
class AccountTests {

    @Autowired
    AccountService accountService;

    MockMvc mockMvc;

    @BeforeEach
    void setup(WebApplicationContext wac) {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    // ...

}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@SpringJUnitWebConfig(locations = [&quot;test-servlet-context.xml&quot;])
class AccountTests {

    @Autowired
    lateinit var accountService: AccountService

    lateinit mockMvc: MockMvc

    @BeforeEach
    fun setup(wac: WebApplicationContext) {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build()
    }

    // ...

}
</code></pre></div><p>The <code>standaloneSetup</code>, on the other hand, is a little closer to a unit test. It tests one
controller at a time. You can manually inject the controller with mock dependencies, and
it does not involve loading Spring configuration. Such tests are more focused on style
and make it easier to see which controller is being tested, whether any specific Spring
MVC configuration is required to work, and so on. The <code>standaloneSetup</code> is also a very
convenient way to write ad-hoc tests to verify specific behavior or to debug an issue.</p> <p>As with most “integration versus unit testing” debates, there is no right or wrong
answer. However, using the <code>standaloneSetup</code> does imply the need for additional<code>webAppContextSetup</code> tests in order to verify your Spring MVC configuration.
Alternatively, you can write all your tests with <code>webAppContextSetup</code>, in order to always
test against your actual Spring MVC configuration.</p> <h5 id="setup-features"><a href="#setup-features" class="header-anchor">#</a> Setup Features</h5> <p>No matter which MockMvc builder you use, all <code>MockMvcBuilder</code> implementations provide
some common and very useful features. For example, you can declare an <code>Accept</code> header for
all requests and expect a status of 200 as well as a <code>Content-Type</code> header in all
responses, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// static import of MockMvcBuilders.standaloneSetup

MockMvc mockMvc = standaloneSetup(new MusicController())
    .defaultRequest(get(&quot;/&quot;).accept(MediaType.APPLICATION_JSON))
    .alwaysExpect(status().isOk())
    .alwaysExpect(content().contentType(&quot;application/json;charset=UTF-8&quot;))
    .build();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed
</code></pre></div><p>In addition, third-party frameworks (and applications) can pre-package setup
instructions, such as those in a <code>MockMvcConfigurer</code>. The Spring Framework has one such
built-in implementation that helps to save and re-use the HTTP session across requests.
You can use it as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// static import of SharedHttpSessionConfigurer.sharedHttpSession

MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new TestController())
        .apply(sharedHttpSession())
        .build();

// Use mockMvc to perform requests...
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed
</code></pre></div><p>See the javadoc for<a href="https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/web/servlet/setup/ConfigurableMockMvcBuilder.html" target="_blank" rel="noopener noreferrer"><code>ConfigurableMockMvcBuilder</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>for a list of all MockMvc builder features or use the IDE to explore the available options.</p> <h5 id="performing-requests"><a href="#performing-requests" class="header-anchor">#</a> Performing Requests</h5> <p>This section shows how to use MockMvc on its own to perform requests and verify responses.
If using MockMvc through the <code>WebTestClient</code> please see the corresponding section on<a href="#webtestclient-tests">Writing Tests</a> instead.</p> <p>To perform requests that use any HTTP method, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// static import of MockMvcRequestBuilders.*

mockMvc.perform(post(&quot;/hotels/{id}&quot;, 42).accept(MediaType.APPLICATION_JSON));
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>import org.springframework.test.web.servlet.post

mockMvc.post(&quot;/hotels/{id}&quot;, 42) {
    accept = MediaType.APPLICATION_JSON
}
</code></pre></div><p>You can also perform file upload requests that internally use<code>MockMultipartHttpServletRequest</code> so that there is no actual parsing of a multipart
request. Rather, you have to set it up to be similar to the following example:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>mockMvc.perform(multipart(&quot;/doc&quot;).file(&quot;a1&quot;, &quot;ABC&quot;.getBytes(&quot;UTF-8&quot;)));
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>import org.springframework.test.web.servlet.multipart

mockMvc.multipart(&quot;/doc&quot;) {
    file(&quot;a1&quot;, &quot;ABC&quot;.toByteArray(charset(&quot;UTF8&quot;)))
}
</code></pre></div><p>You can specify query parameters in URI template style, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>mockMvc.perform(get(&quot;/hotels?thing={thing}&quot;, &quot;somewhere&quot;));
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>mockMvc.get(&quot;/hotels?thing={thing}&quot;, &quot;somewhere&quot;)
</code></pre></div><p>You can also add Servlet request parameters that represent either query or form
parameters, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>mockMvc.perform(get(&quot;/hotels&quot;).param(&quot;thing&quot;, &quot;somewhere&quot;));
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>import org.springframework.test.web.servlet.get

mockMvc.get(&quot;/hotels&quot;) {
    param(&quot;thing&quot;, &quot;somewhere&quot;)
}
</code></pre></div><p>If application code relies on Servlet request parameters and does not check the query
string explicitly (as is most often the case), it does not matter which option you use.
Keep in mind, however, that query parameters provided with the URI template are decoded
while request parameters provided through the <code>param(…​)</code> method are expected to already
be decoded.</p> <p>In most cases, it is preferable to leave the context path and the Servlet path out of the
request URI. If you must test with the full request URI, be sure to set the <code>contextPath</code>and <code>servletPath</code> accordingly so that request mappings work, as the following example
shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>mockMvc.perform(get(&quot;/app/main/hotels/{id}&quot;).contextPath(&quot;/app&quot;).servletPath(&quot;/main&quot;))
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>import org.springframework.test.web.servlet.get

mockMvc.get(&quot;/app/main/hotels/{id}&quot;) {
    contextPath = &quot;/app&quot;
    servletPath = &quot;/main&quot;
}
</code></pre></div><p>In the preceding example, it would be cumbersome to set the <code>contextPath</code> and<code>servletPath</code> with every performed request. Instead, you can set up default request
properties, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>class MyWebTests {

    MockMvc mockMvc;

    @BeforeEach
    void setup() {
        mockMvc = standaloneSetup(new AccountController())
            .defaultRequest(get(&quot;/&quot;)
            .contextPath(&quot;/app&quot;).servletPath(&quot;/main&quot;)
            .accept(MediaType.APPLICATION_JSON)).build();
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed
</code></pre></div><p>The preceding properties affect every request performed through the <code>MockMvc</code> instance.
If the same property is also specified on a given request, it overrides the default
value. That is why the HTTP method and URI in the default request do not matter, since
they must be specified on every request.</p> <h5 id="defining-expectations"><a href="#defining-expectations" class="header-anchor">#</a> Defining Expectations</h5> <p>You can define expectations by appending one or more <code>andExpect(..)</code> calls after
performing a request, as the following example shows. As soon as one expectation fails,
no other expectations will be asserted.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// static import of MockMvcRequestBuilders.* and MockMvcResultMatchers.*

mockMvc.perform(get(&quot;/accounts/1&quot;)).andExpect(status().isOk());
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>import org.springframework.test.web.servlet.get

mockMvc.get(&quot;/accounts/1&quot;).andExpect {
    status().isOk()
}
</code></pre></div><p>You can define multiple expectations by appending <code>andExpectAll(..)</code> after performing a
request, as the following example shows. In contrast to <code>andExpect(..)</code>,<code>andExpectAll(..)</code> guarantees that all supplied expectations will be asserted and that
all failures will be tracked and reported.</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// static import of MockMvcRequestBuilders.* and MockMvcResultMatchers.*

mockMvc.perform(get(&quot;/accounts/1&quot;)).andExpectAll(
    status().isOk(),
    content().contentType(&quot;application/json;charset=UTF-8&quot;));
</code></pre></div><p><code>MockMvcResultMatchers.*</code> provides a number of expectations, some of which are further
nested with more detailed expectations.</p> <p>Expectations fall in two general categories. The first category of assertions verifies
properties of the response (for example, the response status, headers, and content).
These are the most important results to assert.</p> <p>The second category of assertions goes beyond the response. These assertions let you
inspect Spring MVC specific aspects, such as which controller method processed the
request, whether an exception was raised and handled, what the content of the model is,
what view was selected, what flash attributes were added, and so on. They also let you
inspect Servlet specific aspects, such as request and session attributes.</p> <p>The following test asserts that binding or validation failed:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>mockMvc.perform(post(&quot;/persons&quot;))
    .andExpect(status().isOk())
    .andExpect(model().attributeHasErrors(&quot;person&quot;));
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>import org.springframework.test.web.servlet.post

mockMvc.post(&quot;/persons&quot;).andExpect {
    status().isOk()
    model {
        attributeHasErrors(&quot;person&quot;)
    }
}
</code></pre></div><p>Many times, when writing tests, it is useful to dump the results of the performed
request. You can do so as follows, where <code>print()</code> is a static import from<code>MockMvcResultHandlers</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>mockMvc.perform(post(&quot;/persons&quot;))
    .andDo(print())
    .andExpect(status().isOk())
    .andExpect(model().attributeHasErrors(&quot;person&quot;));
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>import org.springframework.test.web.servlet.post

mockMvc.post(&quot;/persons&quot;).andDo {
        print()
    }.andExpect {
        status().isOk()
        model {
            attributeHasErrors(&quot;person&quot;)
        }
    }
</code></pre></div><p>As long as request processing does not cause an unhandled exception, the <code>print()</code> method
prints all the available result data to <code>System.out</code>. There is also a <code>log()</code> method and
two additional variants of the <code>print()</code> method, one that accepts an <code>OutputStream</code> and
one that accepts a <code>Writer</code>. For example, invoking <code>print(System.err)</code> prints the result
data to <code>System.err</code>, while invoking <code>print(myWriter)</code> prints the result data to a custom
writer. If you want to have the result data logged instead of printed, you can invoke the<code>log()</code> method, which logs the result data as a single <code>DEBUG</code> message under the<code>org.springframework.test.web.servlet.result</code> logging category.</p> <p>In some cases, you may want to get direct access to the result and verify something that
cannot be verified otherwise. This can be achieved by appending <code>.andReturn()</code> after all
other expectations, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>MvcResult mvcResult = mockMvc.perform(post(&quot;/persons&quot;)).andExpect(status().isOk()).andReturn();
// ...
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>var mvcResult = mockMvc.post(&quot;/persons&quot;).andExpect { status().isOk() }.andReturn()
// ...
</code></pre></div><p>If all tests repeat the same expectations, you can set up common expectations once when
building the <code>MockMvc</code> instance, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>standaloneSetup(new SimpleController())
    .alwaysExpect(status().isOk())
    .alwaysExpect(content().contentType(&quot;application/json;charset=UTF-8&quot;))
    .build()
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed
</code></pre></div><p>Note that common expectations are always applied and cannot be overridden without
creating a separate <code>MockMvc</code> instance.</p> <p>When a JSON response content contains hypermedia links created with<a href="https://github.com/spring-projects/spring-hateoas" target="_blank" rel="noopener noreferrer">Spring HATEOAS<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>, you can verify the
resulting links by using JsonPath expressions, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>mockMvc.perform(get(&quot;/people&quot;).accept(MediaType.APPLICATION_JSON))
    .andExpect(jsonPath(&quot;$.links[?(@.rel == 'self')].href&quot;).value(&quot;http://localhost:8080/people&quot;));
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>mockMvc.get(&quot;/people&quot;) {
    accept(MediaType.APPLICATION_JSON)
}.andExpect {
    jsonPath(&quot;$.links[?(@.rel == 'self')].href&quot;) {
        value(&quot;http://localhost:8080/people&quot;)
    }
}
</code></pre></div><p>When XML response content contains hypermedia links created with<a href="https://github.com/spring-projects/spring-hateoas" target="_blank" rel="noopener noreferrer">Spring HATEOAS<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>, you can verify the
resulting links by using XPath expressions:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>Map&lt;String, String&gt; ns = Collections.singletonMap(&quot;ns&quot;, &quot;http://www.w3.org/2005/Atom&quot;);
mockMvc.perform(get(&quot;/handle&quot;).accept(MediaType.APPLICATION_XML))
    .andExpect(xpath(&quot;/person/ns:link[@rel='self']/@href&quot;, ns).string(&quot;http://localhost:8080/people&quot;));
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val ns = mapOf(&quot;ns&quot; to &quot;http://www.w3.org/2005/Atom&quot;)
mockMvc.get(&quot;/handle&quot;) {
    accept(MediaType.APPLICATION_XML)
}.andExpect {
    xpath(&quot;/person/ns:link[@rel='self']/@href&quot;, ns) {
        string(&quot;http://localhost:8080/people&quot;)
    }
}
</code></pre></div><h5 id="async-requests"><a href="#async-requests" class="header-anchor">#</a> Async Requests</h5> <p>This section shows how to use MockMvc on its own to test asynchronous request handling.
If using MockMvc through the <a href="#webtestclient">WebTestClient</a>, there is nothing special to do to make
asynchronous requests work as the <code>WebTestClient</code> automatically does what is described
in this section.</p> <p>Servlet 3.0 asynchronous requests,<a href="/en/spring-framework/web.html#mvc-ann-async">supported in Spring MVC</a>, work by exiting the Servlet container
thread and allowing the application to compute the response asynchronously, after which
an async dispatch is made to complete processing on a Servlet container thread.</p> <p>In Spring MVC Test, async requests can be tested by asserting the produced async value
first, then manually performing the async dispatch, and finally verifying the response.
Below is an example test for controller methods that return <code>DeferredResult</code>, <code>Callable</code>,
or reactive type such as Reactor <code>Mono</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>// static import of MockMvcRequestBuilders.* and MockMvcResultMatchers.*

@Test
void test() throws Exception {
    MvcResult mvcResult = this.mockMvc.perform(get(&quot;/path&quot;))
            .andExpect(status().isOk()) (1)
            .andExpect(request().asyncStarted()) (2)
            .andExpect(request().asyncResult(&quot;body&quot;)) (3)
            .andReturn();

    this.mockMvc.perform(asyncDispatch(mvcResult)) (4)
            .andExpect(status().isOk()) (5)
            .andExpect(content().string(&quot;body&quot;));
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Check response status is still unchanged</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Async processing must have started</td></tr> <tr><td><strong>3</strong></td> <td>Wait and assert the async result</td></tr> <tr><td><strong>4</strong></td> <td>Manually perform an ASYNC dispatch (as there is no running container)</td></tr> <tr><td><strong>5</strong></td> <td>Verify the final response</td></tr></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
fun test() {
    var mvcResult = mockMvc.get(&quot;/path&quot;).andExpect {
        status().isOk() (1)
        request { asyncStarted() } (2)
        // TODO Remove unused generic parameter
        request { asyncResult&lt;Nothing&gt;(&quot;body&quot;) } (3)
    }.andReturn()

    mockMvc.perform(asyncDispatch(mvcResult)) (4)
            .andExpect {
                status().isOk() (5)
                content().string(&quot;body&quot;)
            }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th>Check response status is still unchanged</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>Async processing must have started</td></tr> <tr><td><strong>3</strong></td> <td>Wait and assert the async result</td></tr> <tr><td><strong>4</strong></td> <td>Manually perform an ASYNC dispatch (as there is no running container)</td></tr> <tr><td><strong>5</strong></td> <td>Verify the final response</td></tr></tbody></table> <h5 id="streaming-responses-2"><a href="#streaming-responses-2" class="header-anchor">#</a> Streaming Responses</h5> <p>The best way to test streaming responses such as Server-Sent Events is through the<a href="#webtestclient">WebTestClient</a> which can be used as a test client to connect to a <code>MockMvc</code> instance
to perform tests on Spring MVC controllers without a running server. For example:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>WebTestClient client = MockMvcWebTestClient.bindToController(new SseController()).build();

FluxExchangeResult&lt;Person&gt; exchangeResult = client.get()
        .uri(&quot;/persons&quot;)
        .exchange()
        .expectStatus().isOk()
        .expectHeader().contentType(&quot;text/event-stream&quot;)
        .returnResult(Person.class);

// Use StepVerifier from Project Reactor to test the streaming response

StepVerifier.create(exchangeResult.getResponseBody())
        .expectNext(new Person(&quot;N0&quot;), new Person(&quot;N1&quot;), new Person(&quot;N2&quot;))
        .expectNextCount(4)
        .consumeNextWith(person -&gt; assertThat(person.getName()).endsWith(&quot;7&quot;))
        .thenCancel()
        .verify();
</code></pre></div><p><code>WebTestClient</code> can also connect to a live server and perform full end-to-end integration
tests. This is also supported in Spring Boot where you can<a href="https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-testing-spring-boot-applications-testing-with-running-server" target="_blank" rel="noopener noreferrer">test a running server<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>.</p> <h5 id="filter-registrations"><a href="#filter-registrations" class="header-anchor">#</a> Filter Registrations</h5> <p>When setting up a <code>MockMvc</code> instance, you can register one or more Servlet <code>Filter</code>instances, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>mockMvc = standaloneSetup(new PersonController()).addFilters(new CharacterEncodingFilter()).build();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed
</code></pre></div><p>Registered filters are invoked through the <code>MockFilterChain</code> from <code>spring-test</code>, and the
last filter delegates to the <code>DispatcherServlet</code>.</p> <h5 id="mockmvc-vs-end-to-end-tests"><a href="#mockmvc-vs-end-to-end-tests" class="header-anchor">#</a> MockMvc vs End-to-End Tests</h5> <p>MockMVc is built on Servlet API mock implementations from the<code>spring-test</code> module and does not rely on a running container. Therefore, there are
some differences when compared to full end-to-end integration tests with an actual
client and a live server running.</p> <p>The easiest way to think about this is by starting with a blank <code>MockHttpServletRequest</code>.
Whatever you add to it is what the request becomes. Things that may catch you by surprise
are that there is no context path by default; no <code>jsessionid</code> cookie; no forwarding,
error, or async dispatches; and, therefore, no actual JSP rendering. Instead,
“forwarded” and “redirected” URLs are saved in the <code>MockHttpServletResponse</code> and can
be asserted with expectations.</p> <p>This means that, if you use JSPs, you can verify the JSP page to which the request was
forwarded, but no HTML is rendered. In other words, the JSP is not invoked. Note,
however, that all other rendering technologies that do not rely on forwarding, such as
Thymeleaf and Freemarker, render HTML to the response body as expected. The same is true
for rendering JSON, XML, and other formats through <code>@ResponseBody</code> methods.</p> <p>Alternatively, you may consider the full end-to-end integration testing support from
Spring Boot with <code>@SpringBootTest</code>. See the<a href="https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-testing" target="_blank" rel="noopener noreferrer">Spring Boot Reference Guide<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>.</p> <p>There are pros and cons for each approach. The options provided in Spring MVC Test are
different stops on the scale from classic unit testing to full integration testing. To be
certain, none of the options in Spring MVC Test fall under the category of classic unit
testing, but they are a little closer to it. For example, you can isolate the web layer
by injecting mocked services into controllers, in which case you are testing the web
layer only through the <code>DispatcherServlet</code> but with actual Spring configuration, as you
might test the data access layer in isolation from the layers above it. Also, you can use
the stand-alone setup, focusing on one controller at a time and manually providing the
configuration required to make it work.</p> <p>Another important distinction when using Spring MVC Test is that, conceptually, such
tests are the server-side, so you can check what handler was used, if an exception was
handled with a HandlerExceptionResolver, what the content of the model is, what binding
errors there were, and other details. That means that it is easier to write expectations,
since the server is not an opaque box, as it is when testing it through an actual HTTP
client. This is generally an advantage of classic unit testing: It is easier to write,
reason about, and debug but does not replace the need for full integration tests. At the
same time, it is important not to lose sight of the fact that the response is the most
important thing to check. In short, there is room here for multiple styles and strategies
of testing even within the same project.</p> <h5 id="further-examples"><a href="#further-examples" class="header-anchor">#</a> Further Examples</h5> <p>The framework’s own tests include<a href="https://github.com/spring-projects/spring-framework/tree/main/spring-test/src/test/java/org/springframework/test/web/servlet/samples" target="_blank" rel="noopener noreferrer">many sample tests<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> intended to show how to use MockMvc on its own or through the<a href="https://github.com/spring-projects/spring-framework/tree/main/spring-test/src/test/java/org/springframework/test/web/servlet/samples/client" target="_blank" rel="noopener noreferrer">WebTestClient<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>. Browse these examples for further ideas.</p> <h4 id="_3-7-2-htmlunit-integration"><a href="#_3-7-2-htmlunit-integration" class="header-anchor">#</a> 3.7.2. HtmlUnit Integration</h4> <p>Spring provides integration between <a href="#spring-mvc-test-server">MockMvc</a> and<a href="http://htmlunit.sourceforge.net/" target="_blank" rel="noopener noreferrer">HtmlUnit<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>. This simplifies performing end-to-end testing
when using HTML-based views. This integration lets you:</p> <ul><li><p>Easily test HTML pages by using tools such as<a href="http://htmlunit.sourceforge.net/" target="_blank" rel="noopener noreferrer">HtmlUnit<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>,<a href="https://www.seleniumhq.org" target="_blank" rel="noopener noreferrer">WebDriver<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>, and<a href="http://www.gebish.org/manual/current/#spock-junit-testng" target="_blank" rel="noopener noreferrer">Geb<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> without the need to
deploy to a Servlet container.</p></li> <li><p>Test JavaScript within pages.</p></li> <li><p>Optionally, test using mock services to speed up testing.</p></li> <li><p>Share logic between in-container end-to-end tests and out-of-container integration tests.</p></li></ul> <table><thead><tr><th></th> <th>MockMvc works with templating technologies that do not rely on a Servlet Container<br>(for example, Thymeleaf, FreeMarker, and others), but it does not work with JSPs, since<br>they rely on the Servlet container.</th></tr></thead> <tbody></tbody></table> <h5 id="why-htmlunit-integration"><a href="#why-htmlunit-integration" class="header-anchor">#</a> Why HtmlUnit Integration?</h5> <p>The most obvious question that comes to mind is “Why do I need this?” The answer is
best found by exploring a very basic sample application. Assume you have a Spring MVC web
application that supports CRUD operations on a <code>Message</code> object. The application also
supports paging through all messages. How would you go about testing it?</p> <p>With Spring MVC Test, we can easily test if we are able to create a <code>Message</code>, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>MockHttpServletRequestBuilder createMessage = post(&quot;/messages/&quot;)
        .param(&quot;summary&quot;, &quot;Spring Rocks&quot;)
        .param(&quot;text&quot;, &quot;In case you didn't know, Spring Rocks!&quot;);

mockMvc.perform(createMessage)
        .andExpect(status().is3xxRedirection())
        .andExpect(redirectedUrl(&quot;/messages/123&quot;));
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@Test
fun test() {
    mockMvc.post(&quot;/messages/&quot;) {
        param(&quot;summary&quot;, &quot;Spring Rocks&quot;)
        param(&quot;text&quot;, &quot;In case you didn't know, Spring Rocks!&quot;)
    }.andExpect {
        status().is3xxRedirection()
        redirectedUrl(&quot;/messages/123&quot;)
    }
}
</code></pre></div><p>What if we want to test the form view that lets us create the message? For example,
assume our form looks like the following snippet:</p> <div class="language- extra-class"><pre class="language-text"><code>&lt;form id=&quot;messageForm&quot; action=&quot;/messages/&quot; method=&quot;post&quot;&gt;
    &lt;div class=&quot;pull-right&quot;&gt;&lt;a href=&quot;/messages/&quot;&gt;Messages&lt;/a&gt;&lt;/div&gt;

    &lt;label for=&quot;summary&quot;&gt;Summary&lt;/label&gt;
    &lt;input type=&quot;text&quot; class=&quot;required&quot; id=&quot;summary&quot; name=&quot;summary&quot; value=&quot;&quot; /&gt;

    &lt;label for=&quot;text&quot;&gt;Message&lt;/label&gt;
    &lt;textarea id=&quot;text&quot; name=&quot;text&quot;&gt;&lt;/textarea&gt;

    &lt;div class=&quot;form-actions&quot;&gt;
        &lt;input type=&quot;submit&quot; value=&quot;Create&quot; /&gt;
    &lt;/div&gt;
&lt;/form&gt;
</code></pre></div><p>How do we ensure that our form produce the correct request to create a new message? A
naive attempt might resemble the following:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>mockMvc.perform(get(&quot;/messages/form&quot;))
        .andExpect(xpath(&quot;//input[@name='summary']&quot;).exists())
        .andExpect(xpath(&quot;//textarea[@name='text']&quot;).exists());
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>mockMvc.get(&quot;/messages/form&quot;).andExpect {
    xpath(&quot;//input[@name='summary']&quot;) { exists() }
    xpath(&quot;//textarea[@name='text']&quot;) { exists() }
}
</code></pre></div><p>This test has some obvious drawbacks. If we update our controller to use the parameter<code>message</code> instead of <code>text</code>, our form test continues to pass, even though the HTML form
is out of synch with the controller. To resolve this we can combine our two tests, as
follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>String summaryParamName = &quot;summary&quot;;
String textParamName = &quot;text&quot;;
mockMvc.perform(get(&quot;/messages/form&quot;))
        .andExpect(xpath(&quot;//input[@name='&quot; + summaryParamName + &quot;']&quot;).exists())
        .andExpect(xpath(&quot;//textarea[@name='&quot; + textParamName + &quot;']&quot;).exists());

MockHttpServletRequestBuilder createMessage = post(&quot;/messages/&quot;)
        .param(summaryParamName, &quot;Spring Rocks&quot;)
        .param(textParamName, &quot;In case you didn't know, Spring Rocks!&quot;);

mockMvc.perform(createMessage)
        .andExpect(status().is3xxRedirection())
        .andExpect(redirectedUrl(&quot;/messages/123&quot;));
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val summaryParamName = &quot;summary&quot;;
val textParamName = &quot;text&quot;;
mockMvc.get(&quot;/messages/form&quot;).andExpect {
    xpath(&quot;//input[@name='$summaryParamName']&quot;) { exists() }
    xpath(&quot;//textarea[@name='$textParamName']&quot;) { exists() }
}
mockMvc.post(&quot;/messages/&quot;) {
    param(summaryParamName, &quot;Spring Rocks&quot;)
    param(textParamName, &quot;In case you didn't know, Spring Rocks!&quot;)
}.andExpect {
    status().is3xxRedirection()
    redirectedUrl(&quot;/messages/123&quot;)
}
</code></pre></div><p>This would reduce the risk of our test incorrectly passing, but there are still some
problems:</p> <ul><li><p>What if we have multiple forms on our page? Admittedly, we could update our XPath
expressions, but they get more complicated as we take more factors into account: Are
the fields the correct type? Are the fields enabled? And so on.</p></li> <li><p>Another issue is that we are doing double the work we would expect. We must first
verify the view, and then we submit the view with the same parameters we just verified.
Ideally, this could be done all at once.</p></li> <li><p>Finally, we still cannot account for some things. For example, what if the form has
JavaScript validation that we wish to test as well?</p></li></ul> <p>The overall problem is that testing a web page does not involve a single interaction.
Instead, it is a combination of how the user interacts with a web page and how that web
page interacts with other resources. For example, the result of a form view is used as
the input to a user for creating a message. In addition, our form view can potentially
use additional resources that impact the behavior of the page, such as JavaScript
validation.</p> <h6 id="integration-testing-to-the-rescue"><a href="#integration-testing-to-the-rescue" class="header-anchor">#</a> Integration Testing to the Rescue?</h6> <p>To resolve the issues mentioned earlier, we could perform end-to-end integration testing,
but this has some drawbacks. Consider testing the view that lets us page through the
messages. We might need the following tests:</p> <ul><li><p>Does our page display a notification to the user to indicate that no results are
available when the messages are empty?</p></li> <li><p>Does our page properly display a single message?</p></li> <li><p>Does our page properly support paging?</p></li></ul> <p>To set up these tests, we need to ensure our database contains the proper messages. This
leads to a number of additional challenges:</p> <ul><li><p>Ensuring the proper messages are in the database can be tedious. (Consider foreign key
constraints.)</p></li> <li><p>Testing can become slow, since each test would need to ensure that the database is in
the correct state.</p></li> <li><p>Since our database needs to be in a specific state, we cannot run tests in parallel.</p></li> <li><p>Performing assertions on such items as auto-generated ids, timestamps, and others can
be difficult.</p></li></ul> <p>These challenges do not mean that we should abandon end-to-end integration testing
altogether. Instead, we can reduce the number of end-to-end integration tests by
refactoring our detailed tests to use mock services that run much faster, more reliably,
and without side effects. We can then implement a small number of true end-to-end
integration tests that validate simple workflows to ensure that everything works together
properly.</p> <h6 id="enter-htmlunit-integration"><a href="#enter-htmlunit-integration" class="header-anchor">#</a> Enter HtmlUnit Integration</h6> <p>So how can we achieve a balance between testing the interactions of our pages and still
retain good performance within our test suite? The answer is: “By integrating MockMvc
with HtmlUnit.”</p> <h6 id="htmlunit-integration-options"><a href="#htmlunit-integration-options" class="header-anchor">#</a> HtmlUnit Integration Options</h6> <p>You have a number of options when you want to integrate MockMvc with HtmlUnit:</p> <ul><li><p><a href="#spring-mvc-test-server-htmlunit-mah">MockMvc and HtmlUnit</a>: Use this option if you
want to use the raw HtmlUnit libraries.</p></li> <li><p><a href="#spring-mvc-test-server-htmlunit-webdriver">MockMvc and WebDriver</a>: Use this option to
ease development and reuse code between integration and end-to-end testing.</p></li> <li><p><a href="#spring-mvc-test-server-htmlunit-geb">MockMvc and Geb</a>: Use this option if you want to
use Groovy for testing, ease development, and reuse code between integration and
end-to-end testing.</p></li></ul> <h5 id="mockmvc-and-htmlunit"><a href="#mockmvc-and-htmlunit" class="header-anchor">#</a> MockMvc and HtmlUnit</h5> <p>This section describes how to integrate MockMvc and HtmlUnit. Use this option if you want
to use the raw HtmlUnit libraries.</p> <h6 id="mockmvc-and-htmlunit-setup"><a href="#mockmvc-and-htmlunit-setup" class="header-anchor">#</a> MockMvc and HtmlUnit Setup</h6> <p>First, make sure that you have included a test dependency on<code>net.sourceforge.htmlunit:htmlunit</code>. In order to use HtmlUnit with Apache HttpComponents
4.5+, you need to use HtmlUnit 2.18 or higher.</p> <p>We can easily create an HtmlUnit <code>WebClient</code> that integrates with MockMvc by using the<code>MockMvcWebClientBuilder</code>, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>WebClient webClient;

@BeforeEach
void setup(WebApplicationContext context) {
    webClient = MockMvcWebClientBuilder
            .webAppContextSetup(context)
            .build();
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>lateinit var webClient: WebClient

@BeforeEach
fun setup(context: WebApplicationContext) {
    webClient = MockMvcWebClientBuilder
            .webAppContextSetup(context)
            .build()
}
</code></pre></div><table><thead><tr><th></th> <th>This is a simple example of using <code>MockMvcWebClientBuilder</code>. For advanced usage,<br>see <a href="#spring-mvc-test-server-htmlunit-mah-advanced-builder">Advanced <code>MockMvcWebClientBuilder</code></a>.</th></tr></thead> <tbody></tbody></table> <p>This ensures that any URL that references <code>localhost</code> as the server is directed to our<code>MockMvc</code> instance without the need for a real HTTP connection. Any other URL is
requested by using a network connection, as normal. This lets us easily test the use of
CDNs.</p> <h6 id="mockmvc-and-htmlunit-usage"><a href="#mockmvc-and-htmlunit-usage" class="header-anchor">#</a> MockMvc and HtmlUnit Usage</h6> <p>Now we can use HtmlUnit as we normally would but without the need to deploy our
application to a Servlet container. For example, we can request the view to create a
message with the following:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>HtmlPage createMsgFormPage = webClient.getPage(&quot;http://localhost/messages/form&quot;);
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val createMsgFormPage = webClient.getPage(&quot;http://localhost/messages/form&quot;)
</code></pre></div><table><thead><tr><th></th> <th>The default context path is <code>&quot;&quot;</code>. Alternatively, we can specify the context path,<br>as described in <a href="#spring-mvc-test-server-htmlunit-mah-advanced-builder">Advanced <code>MockMvcWebClientBuilder</code></a>.</th></tr></thead> <tbody></tbody></table> <p>Once we have a reference to the <code>HtmlPage</code>, we can then fill out the form and submit it
to create a message, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>HtmlForm form = createMsgFormPage.getHtmlElementById(&quot;messageForm&quot;);
HtmlTextInput summaryInput = createMsgFormPage.getHtmlElementById(&quot;summary&quot;);
summaryInput.setValueAttribute(&quot;Spring Rocks&quot;);
HtmlTextArea textInput = createMsgFormPage.getHtmlElementById(&quot;text&quot;);
textInput.setText(&quot;In case you didn't know, Spring Rocks!&quot;);
HtmlSubmitInput submit = form.getOneHtmlElementByAttribute(&quot;input&quot;, &quot;type&quot;, &quot;submit&quot;);
HtmlPage newMessagePage = submit.click();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val form = createMsgFormPage.getHtmlElementById(&quot;messageForm&quot;)
val summaryInput = createMsgFormPage.getHtmlElementById(&quot;summary&quot;)
summaryInput.setValueAttribute(&quot;Spring Rocks&quot;)
val textInput = createMsgFormPage.getHtmlElementById(&quot;text&quot;)
textInput.setText(&quot;In case you didn't know, Spring Rocks!&quot;)
val submit = form.getOneHtmlElementByAttribute(&quot;input&quot;, &quot;type&quot;, &quot;submit&quot;)
val newMessagePage = submit.click()
</code></pre></div><p>Finally, we can verify that a new message was created successfully. The following
assertions use the <a href="https://assertj.github.io/doc/" target="_blank" rel="noopener noreferrer">AssertJ<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> library:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>assertThat(newMessagePage.getUrl().toString()).endsWith(&quot;/messages/123&quot;);
String id = newMessagePage.getHtmlElementById(&quot;id&quot;).getTextContent();
assertThat(id).isEqualTo(&quot;123&quot;);
String summary = newMessagePage.getHtmlElementById(&quot;summary&quot;).getTextContent();
assertThat(summary).isEqualTo(&quot;Spring Rocks&quot;);
String text = newMessagePage.getHtmlElementById(&quot;text&quot;).getTextContent();
assertThat(text).isEqualTo(&quot;In case you didn't know, Spring Rocks!&quot;);
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>assertThat(newMessagePage.getUrl().toString()).endsWith(&quot;/messages/123&quot;)
val id = newMessagePage.getHtmlElementById(&quot;id&quot;).getTextContent()
assertThat(id).isEqualTo(&quot;123&quot;)
val summary = newMessagePage.getHtmlElementById(&quot;summary&quot;).getTextContent()
assertThat(summary).isEqualTo(&quot;Spring Rocks&quot;)
val text = newMessagePage.getHtmlElementById(&quot;text&quot;).getTextContent()
assertThat(text).isEqualTo(&quot;In case you didn't know, Spring Rocks!&quot;)
</code></pre></div><p>The preceding code improves on our<a href="#spring-mvc-test-server-htmlunit-mock-mvc-test">MockMvc test</a> in a number of ways.
First, we no longer have to explicitly verify our form and then create a request that
looks like the form. Instead, we request the form, fill it out, and submit it, thereby
significantly reducing the overhead.</p> <p>Another important factor is that <a href="http://htmlunit.sourceforge.net/javascript.html" target="_blank" rel="noopener noreferrer">HtmlUnit
uses the Mozilla Rhino engine<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> to evaluate JavaScript. This means that we can also test
the behavior of JavaScript within our pages.</p> <p>See the <a href="http://htmlunit.sourceforge.net/gettingStarted.html" target="_blank" rel="noopener noreferrer">HtmlUnit documentation<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> for
additional information about using HtmlUnit.</p> <h6 id="advanced-mockmvcwebclientbuilder"><a href="#advanced-mockmvcwebclientbuilder" class="header-anchor">#</a> Advanced <code>MockMvcWebClientBuilder</code></h6> <p>In the examples so far, we have used <code>MockMvcWebClientBuilder</code> in the simplest way
possible, by building a <code>WebClient</code> based on the <code>WebApplicationContext</code> loaded for us by
the Spring TestContext Framework. This approach is repeated in the following example:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>WebClient webClient;

@BeforeEach
void setup(WebApplicationContext context) {
    webClient = MockMvcWebClientBuilder
            .webAppContextSetup(context)
            .build();
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>lateinit var webClient: WebClient

@BeforeEach
fun setup(context: WebApplicationContext) {
    webClient = MockMvcWebClientBuilder
            .webAppContextSetup(context)
            .build()
}
</code></pre></div><p>We can also specify additional configuration options, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>WebClient webClient;

@BeforeEach
void setup() {
    webClient = MockMvcWebClientBuilder
        // demonstrates applying a MockMvcConfigurer (Spring Security)
        .webAppContextSetup(context, springSecurity())
        // for illustration only - defaults to &quot;&quot;
        .contextPath(&quot;&quot;)
        // By default MockMvc is used for localhost only;
        // the following will use MockMvc for example.com and example.org as well
        .useMockMvcForHosts(&quot;example.com&quot;,&quot;example.org&quot;)
        .build();
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>lateinit var webClient: WebClient

@BeforeEach
fun setup() {
    webClient = MockMvcWebClientBuilder
        // demonstrates applying a MockMvcConfigurer (Spring Security)
        .webAppContextSetup(context, springSecurity())
        // for illustration only - defaults to &quot;&quot;
        .contextPath(&quot;&quot;)
        // By default MockMvc is used for localhost only;
        // the following will use MockMvc for example.com and example.org as well
        .useMockMvcForHosts(&quot;example.com&quot;,&quot;example.org&quot;)
        .build()
}
</code></pre></div><p>As an alternative, we can perform the exact same setup by configuring the <code>MockMvc</code>instance separately and supplying it to the <code>MockMvcWebClientBuilder</code>, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>MockMvc mockMvc = MockMvcBuilders
        .webAppContextSetup(context)
        .apply(springSecurity())
        .build();

webClient = MockMvcWebClientBuilder
        .mockMvcSetup(mockMvc)
        // for illustration only - defaults to &quot;&quot;
        .contextPath(&quot;&quot;)
        // By default MockMvc is used for localhost only;
        // the following will use MockMvc for example.com and example.org as well
        .useMockMvcForHosts(&quot;example.com&quot;,&quot;example.org&quot;)
        .build();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed
</code></pre></div><p>This is more verbose, but, by building the <code>WebClient</code> with a <code>MockMvc</code> instance, we have
the full power of MockMvc at our fingertips.</p> <table><thead><tr><th></th> <th>For additional information on creating a <code>MockMvc</code> instance, see<a href="#spring-mvc-test-server-setup-options">Setup Choices</a>.</th></tr></thead> <tbody></tbody></table> <h5 id="mockmvc-and-webdriver"><a href="#mockmvc-and-webdriver" class="header-anchor">#</a> MockMvc and WebDriver</h5> <p>In the previous sections, we have seen how to use MockMvc in conjunction with the raw
HtmlUnit APIs. In this section, we use additional abstractions within the Selenium<a href="https://docs.seleniumhq.org/projects/webdriver/" target="_blank" rel="noopener noreferrer">WebDriver<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> to make things even easier.</p> <h6 id="why-webdriver-and-mockmvc"><a href="#why-webdriver-and-mockmvc" class="header-anchor">#</a> Why WebDriver and MockMvc?</h6> <p>We can already use HtmlUnit and MockMvc, so why would we want to use WebDriver? The
Selenium WebDriver provides a very elegant API that lets us easily organize our code. To
better show how it works, we explore an example in this section.</p> <table><thead><tr><th></th> <th>Despite being a part of <a href="https://docs.seleniumhq.org/" target="_blank" rel="noopener noreferrer">Selenium<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>, WebDriver does not<br>require a Selenium Server to run your tests.</th></tr></thead> <tbody></tbody></table> <p>Suppose we need to ensure that a message is created properly. The tests involve finding
the HTML form input elements, filling them out, and making various assertions.</p> <p>This approach results in numerous separate tests because we want to test error conditions
as well. For example, we want to ensure that we get an error if we fill out only part of
the form. If we fill out the entire form, the newly created message should be displayed
afterwards.</p> <p>If one of the fields were named “summary”, we might have something that resembles the
following repeated in multiple places within our tests:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>HtmlTextInput summaryInput = currentPage.getHtmlElementById(&quot;summary&quot;);
summaryInput.setValueAttribute(summary);
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val summaryInput = currentPage.getHtmlElementById(&quot;summary&quot;)
summaryInput.setValueAttribute(summary)
</code></pre></div><p>So what happens if we change the <code>id</code> to <code>smmry</code>? Doing so would force us to update all
of our tests to incorporate this change. This violates the DRY principle, so we should
ideally extract this code into its own method, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>public HtmlPage createMessage(HtmlPage currentPage, String summary, String text) {
    setSummary(currentPage, summary);
    // ...
}

public void setSummary(HtmlPage currentPage, String summary) {
    HtmlTextInput summaryInput = currentPage.getHtmlElementById(&quot;summary&quot;);
    summaryInput.setValueAttribute(summary);
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>fun createMessage(currentPage: HtmlPage, summary:String, text:String) :HtmlPage{
    setSummary(currentPage, summary);
    // ...
}

fun setSummary(currentPage:HtmlPage , summary: String) {
    val summaryInput = currentPage.getHtmlElementById(&quot;summary&quot;)
    summaryInput.setValueAttribute(summary)
}
</code></pre></div><p>Doing so ensures that we do not have to update all of our tests if we change the UI.</p> <p>We might even take this a step further and place this logic within an <code>Object</code> that
represents the <code>HtmlPage</code> we are currently on, as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>public class CreateMessagePage {

    final HtmlPage currentPage;

    final HtmlTextInput summaryInput;

    final HtmlSubmitInput submit;

    public CreateMessagePage(HtmlPage currentPage) {
        this.currentPage = currentPage;
        this.summaryInput = currentPage.getHtmlElementById(&quot;summary&quot;);
        this.submit = currentPage.getHtmlElementById(&quot;submit&quot;);
    }

    public &lt;T&gt; T createMessage(String summary, String text) throws Exception {
        setSummary(summary);

        HtmlPage result = submit.click();
        boolean error = CreateMessagePage.at(result);

        return (T) (error ? new CreateMessagePage(result) : new ViewMessagePage(result));
    }

    public void setSummary(String summary) throws Exception {
        summaryInput.setValueAttribute(summary);
    }

    public static boolean at(HtmlPage page) {
        return &quot;Create Message&quot;.equals(page.getTitleText());
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>    class CreateMessagePage(private val currentPage: HtmlPage) {

        val summaryInput: HtmlTextInput = currentPage.getHtmlElementById(&quot;summary&quot;)

        val submit: HtmlSubmitInput = currentPage.getHtmlElementById(&quot;submit&quot;)

        fun &lt;T&gt; createMessage(summary: String, text: String): T {
            setSummary(summary)

            val result = submit.click()
            val error = at(result)

            return (if (error) CreateMessagePage(result) else ViewMessagePage(result)) as T
        }

        fun setSummary(summary: String) {
            summaryInput.setValueAttribute(summary)
        }

        fun at(page: HtmlPage): Boolean {
            return &quot;Create Message&quot; == page.getTitleText()
        }
    }
}
</code></pre></div><p>Formerly, this pattern was known as the<a href="https://github.com/SeleniumHQ/selenium/wiki/PageObjects" target="_blank" rel="noopener noreferrer">Page Object Pattern<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>. While we
can certainly do this with HtmlUnit, WebDriver provides some tools that we explore in the
following sections to make this pattern much easier to implement.</p> <h6 id="mockmvc-and-webdriver-setup"><a href="#mockmvc-and-webdriver-setup" class="header-anchor">#</a> MockMvc and WebDriver Setup</h6> <p>To use Selenium WebDriver with the Spring MVC Test framework, make sure that your project
includes a test dependency on <code>org.seleniumhq.selenium:selenium-htmlunit-driver</code>.</p> <p>We can easily create a Selenium WebDriver that integrates with MockMvc by using the<code>MockMvcHtmlUnitDriverBuilder</code> as the following example shows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>WebDriver driver;

@BeforeEach
void setup(WebApplicationContext context) {
    driver = MockMvcHtmlUnitDriverBuilder
            .webAppContextSetup(context)
            .build();
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>lateinit var driver: WebDriver

@BeforeEach
fun setup(context: WebApplicationContext) {
    driver = MockMvcHtmlUnitDriverBuilder
            .webAppContextSetup(context)
            .build()
}
</code></pre></div><table><thead><tr><th></th> <th>This is a simple example of using <code>MockMvcHtmlUnitDriverBuilder</code>. For more advanced<br>usage, see <a href="#spring-mvc-test-server-htmlunit-webdriver-advanced-builder">Advanced <code>MockMvcHtmlUnitDriverBuilder</code></a>.</th></tr></thead> <tbody></tbody></table> <p>The preceding example ensures that any URL that references <code>localhost</code> as the server is
directed to our <code>MockMvc</code> instance without the need for a real HTTP connection. Any other
URL is requested by using a network connection, as normal. This lets us easily test the
use of CDNs.</p> <h6 id="mockmvc-and-webdriver-usage"><a href="#mockmvc-and-webdriver-usage" class="header-anchor">#</a> MockMvc and WebDriver Usage</h6> <p>Now we can use WebDriver as we normally would but without the need to deploy our
application to a Servlet container. For example, we can request the view to create a
message with the following:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>CreateMessagePage page = CreateMessagePage.to(driver);
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val page = CreateMessagePage.to(driver)
</code></pre></div><p>We can then fill out the form and submit it to create a message, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>ViewMessagePage viewMessagePage =
        page.createMessage(ViewMessagePage.class, expectedSummary, expectedText);
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val viewMessagePage =
    page.createMessage(ViewMessagePage::class, expectedSummary, expectedText)
</code></pre></div><p>This improves on the design of our <a href="#spring-mvc-test-server-htmlunit-mah-usage">HtmlUnit test</a>by leveraging the Page Object Pattern. As we mentioned in<a href="#spring-mvc-test-server-htmlunit-webdriver-why">Why WebDriver and MockMvc?</a>, we can use the Page Object Pattern
with HtmlUnit, but it is much easier with WebDriver. Consider the following<code>CreateMessagePage</code> implementation:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>public class CreateMessagePage
        extends AbstractPage { (1)

    (2)
    private WebElement summary;
    private WebElement text;

    (3)
    @FindBy(css = &quot;input[type=submit]&quot;)
    private WebElement submit;

    public CreateMessagePage(WebDriver driver) {
        super(driver);
    }

    public &lt;T&gt; T createMessage(Class&lt;T&gt; resultPage, String summary, String details) {
        this.summary.sendKeys(summary);
        this.text.sendKeys(details);
        this.submit.click();
        return PageFactory.initElements(driver, resultPage);
    }

    public static CreateMessagePage to(WebDriver driver) {
        driver.get(&quot;http://localhost:9990/mail/messages/form&quot;);
        return PageFactory.initElements(driver, CreateMessagePage.class);
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th><code>CreateMessagePage</code> extends the <code>AbstractPage</code>. We do not go over the details of<code>AbstractPage</code>, but, in summary, it contains common functionality for all of our pages.<br>For example, if our application has a navigational bar, global error messages, and other<br>features, we can place this logic in a shared location.</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>We have a member variable for each of the parts of the HTML page in which we are<br>interested. These are of type <code>WebElement</code>. WebDriver’s<a href="https://github.com/SeleniumHQ/selenium/wiki/PageFactory" target="_blank" rel="noopener noreferrer"><code>PageFactory</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> lets us remove a<br>lot of code from the HtmlUnit version of <code>CreateMessagePage</code> by automatically resolving<br>each <code>WebElement</code>. The<a href="https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/PageFactory.html#initElements-org.openqa.selenium.WebDriver-java.lang.Class-" target="_blank" rel="noopener noreferrer"><code>PageFactory#initElements(WebDriver,Class&lt;T&gt;)</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>method automatically resolves each <code>WebElement</code> by using the field name and looking it up<br>by the <code>id</code> or <code>name</code> of the element within the HTML page.</td></tr> <tr><td><strong>3</strong></td> <td>We can use the<a href="https://github.com/SeleniumHQ/selenium/wiki/PageFactory#making-the-example-work-using-annotations" target="_blank" rel="noopener noreferrer"><code>@FindBy</code> annotation<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>to override the default lookup behavior. Our example shows how to use the <code>@FindBy</code>annotation to look up our submit button with a <code>css</code> selector (<strong>input[type=submit]</strong>).</td></tr></tbody></table> <p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>class CreateMessagePage(private val driver: WebDriver) : AbstractPage(driver) { (1)

    (2)
    private lateinit var summary: WebElement
    private lateinit var text: WebElement

    (3)
    @FindBy(css = &quot;input[type=submit]&quot;)
    private lateinit var submit: WebElement

    fun &lt;T&gt; createMessage(resultPage: Class&lt;T&gt;, summary: String, details: String): T {
        this.summary.sendKeys(summary)
        text.sendKeys(details)
        submit.click()
        return PageFactory.initElements(driver, resultPage)
    }
    companion object {
        fun to(driver: WebDriver): CreateMessagePage {
            driver.get(&quot;http://localhost:9990/mail/messages/form&quot;)
            return PageFactory.initElements(driver, CreateMessagePage::class.java)
        }
    }
}
</code></pre></div><table><thead><tr><th><strong>1</strong></th> <th><code>CreateMessagePage</code> extends the <code>AbstractPage</code>. We do not go over the details of<code>AbstractPage</code>, but, in summary, it contains common functionality for all of our pages.<br>For example, if our application has a navigational bar, global error messages, and other<br>features, we can place this logic in a shared location.</th></tr></thead> <tbody><tr><td><strong>2</strong></td> <td>We have a member variable for each of the parts of the HTML page in which we are<br>interested. These are of type <code>WebElement</code>. WebDriver’s<a href="https://github.com/SeleniumHQ/selenium/wiki/PageFactory" target="_blank" rel="noopener noreferrer"><code>PageFactory</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> lets us remove a<br>lot of code from the HtmlUnit version of <code>CreateMessagePage</code> by automatically resolving<br>each <code>WebElement</code>. The<a href="https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/PageFactory.html#initElements-org.openqa.selenium.WebDriver-java.lang.Class-" target="_blank" rel="noopener noreferrer"><code>PageFactory#initElements(WebDriver,Class&lt;T&gt;)</code><span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>method automatically resolves each <code>WebElement</code> by using the field name and looking it up<br>by the <code>id</code> or <code>name</code> of the element within the HTML page.</td></tr> <tr><td><strong>3</strong></td> <td>We can use the<a href="https://github.com/SeleniumHQ/selenium/wiki/PageFactory#making-the-example-work-using-annotations" target="_blank" rel="noopener noreferrer"><code>@FindBy</code> annotation<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>to override the default lookup behavior. Our example shows how to use the <code>@FindBy</code>annotation to look up our submit button with a <code>css</code> selector (<strong>input[type=submit]</strong>).</td></tr></tbody></table> <p>Finally, we can verify that a new message was created successfully. The following
assertions use the <a href="https://assertj.github.io/doc/" target="_blank" rel="noopener noreferrer">AssertJ<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> assertion library:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>assertThat(viewMessagePage.getMessage()).isEqualTo(expectedMessage);
assertThat(viewMessagePage.getSuccess()).isEqualTo(&quot;Successfully created a new message&quot;);
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>assertThat(viewMessagePage.message).isEqualTo(expectedMessage)
assertThat(viewMessagePage.success).isEqualTo(&quot;Successfully created a new message&quot;)
</code></pre></div><p>We can see that our <code>ViewMessagePage</code> lets us interact with our custom domain model. For
example, it exposes a method that returns a <code>Message</code> object:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>public Message getMessage() throws ParseException {
    Message message = new Message();
    message.setId(getId());
    message.setCreated(getCreated());
    message.setSummary(getSummary());
    message.setText(getText());
    return message;
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>fun getMessage() = Message(getId(), getCreated(), getSummary(), getText())
</code></pre></div><p>We can then use the rich domain objects in our assertions.</p> <p>Lastly, we must not forget to close the <code>WebDriver</code> instance when the test is complete,
as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>@AfterEach
void destroy() {
    if (driver != null) {
        driver.close();
    }
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>@AfterEach
fun destroy() {
    if (driver != null) {
        driver.close()
    }
}
</code></pre></div><p>For additional information on using WebDriver, see the Selenium<a href="https://github.com/SeleniumHQ/selenium/wiki/Getting-Started" target="_blank" rel="noopener noreferrer">WebDriver documentation<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>.</p> <h6 id="advanced-mockmvchtmlunitdriverbuilder"><a href="#advanced-mockmvchtmlunitdriverbuilder" class="header-anchor">#</a> Advanced <code>MockMvcHtmlUnitDriverBuilder</code></h6> <p>In the examples so far, we have used <code>MockMvcHtmlUnitDriverBuilder</code> in the simplest way
possible, by building a <code>WebDriver</code> based on the <code>WebApplicationContext</code> loaded for us by
the Spring TestContext Framework. This approach is repeated here, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>WebDriver driver;

@BeforeEach
void setup(WebApplicationContext context) {
    driver = MockMvcHtmlUnitDriverBuilder
            .webAppContextSetup(context)
            .build();
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>lateinit var driver: WebDriver

@BeforeEach
fun setup(context: WebApplicationContext) {
    driver = MockMvcHtmlUnitDriverBuilder
            .webAppContextSetup(context)
            .build()
}
</code></pre></div><p>We can also specify additional configuration options, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>WebDriver driver;

@BeforeEach
void setup() {
    driver = MockMvcHtmlUnitDriverBuilder
            // demonstrates applying a MockMvcConfigurer (Spring Security)
            .webAppContextSetup(context, springSecurity())
            // for illustration only - defaults to &quot;&quot;
            .contextPath(&quot;&quot;)
            // By default MockMvc is used for localhost only;
            // the following will use MockMvc for example.com and example.org as well
            .useMockMvcForHosts(&quot;example.com&quot;,&quot;example.org&quot;)
            .build();
}
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>lateinit var driver: WebDriver

@BeforeEach
fun setup() {
    driver = MockMvcHtmlUnitDriverBuilder
            // demonstrates applying a MockMvcConfigurer (Spring Security)
            .webAppContextSetup(context, springSecurity())
            // for illustration only - defaults to &quot;&quot;
            .contextPath(&quot;&quot;)
            // By default MockMvc is used for localhost only;
            // the following will use MockMvc for example.com and example.org as well
            .useMockMvcForHosts(&quot;example.com&quot;,&quot;example.org&quot;)
            .build()
}
</code></pre></div><p>As an alternative, we can perform the exact same setup by configuring the <code>MockMvc</code>instance separately and supplying it to the <code>MockMvcHtmlUnitDriverBuilder</code>, as follows:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>MockMvc mockMvc = MockMvcBuilders
        .webAppContextSetup(context)
        .apply(springSecurity())
        .build();

driver = MockMvcHtmlUnitDriverBuilder
        .mockMvcSetup(mockMvc)
        // for illustration only - defaults to &quot;&quot;
        .contextPath(&quot;&quot;)
        // By default MockMvc is used for localhost only;
        // the following will use MockMvc for example.com and example.org as well
        .useMockMvcForHosts(&quot;example.com&quot;,&quot;example.org&quot;)
        .build();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed
</code></pre></div><p>This is more verbose, but, by building the <code>WebDriver</code> with a <code>MockMvc</code> instance, we have
the full power of MockMvc at our fingertips.</p> <table><thead><tr><th></th> <th>For additional information on creating a <code>MockMvc</code> instance, see<a href="#spring-mvc-test-server-setup-options">Setup Choices</a>.</th></tr></thead> <tbody></tbody></table> <h5 id="mockmvc-and-geb"><a href="#mockmvc-and-geb" class="header-anchor">#</a> MockMvc and Geb</h5> <p>In the previous section, we saw how to use MockMvc with WebDriver. In this section, we
use <a href="http://www.gebish.org/" target="_blank" rel="noopener noreferrer">Geb<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> to make our tests even Groovy-er.</p> <h6 id="why-geb-and-mockmvc"><a href="#why-geb-and-mockmvc" class="header-anchor">#</a> Why Geb and MockMvc?</h6> <p>Geb is backed by WebDriver, so it offers many of the<a href="#spring-mvc-test-server-htmlunit-webdriver-why">same benefits</a> that we get from
WebDriver. However, Geb makes things even easier by taking care of some of the
boilerplate code for us.</p> <h6 id="mockmvc-and-geb-setup"><a href="#mockmvc-and-geb-setup" class="header-anchor">#</a> MockMvc and Geb Setup</h6> <p>We can easily initialize a Geb <code>Browser</code> with a Selenium WebDriver that uses MockMvc, as
follows:</p> <div class="language- extra-class"><pre class="language-text"><code>def setup() {
    browser.driver = MockMvcHtmlUnitDriverBuilder
        .webAppContextSetup(context)
        .build()
}
</code></pre></div><table><thead><tr><th></th> <th>This is a simple example of using <code>MockMvcHtmlUnitDriverBuilder</code>. For more advanced<br>usage, see <a href="#spring-mvc-test-server-htmlunit-webdriver-advanced-builder">Advanced <code>MockMvcHtmlUnitDriverBuilder</code></a>.</th></tr></thead> <tbody></tbody></table> <p>This ensures that any URL referencing <code>localhost</code> as the server is directed to our<code>MockMvc</code> instance without the need for a real HTTP connection. Any other URL is
requested by using a network connection as normal. This lets us easily test the use of
CDNs.</p> <h6 id="mockmvc-and-geb-usage"><a href="#mockmvc-and-geb-usage" class="header-anchor">#</a> MockMvc and Geb Usage</h6> <p>Now we can use Geb as we normally would but without the need to deploy our application to
a Servlet container. For example, we can request the view to create a message with the
following:</p> <div class="language- extra-class"><pre class="language-text"><code>to CreateMessagePage
</code></pre></div><p>We can then fill out the form and submit it to create a message, as follows:</p> <div class="language- extra-class"><pre class="language-text"><code>when:
form.summary = expectedSummary
form.text = expectedMessage
submit.click(ViewMessagePage)
</code></pre></div><p>Any unrecognized method calls or property accesses or references that are not found are
forwarded to the current page object. This removes a lot of the boilerplate code we
needed when using WebDriver directly.</p> <p>As with direct WebDriver usage, this improves on the design of our<a href="#spring-mvc-test-server-htmlunit-mah-usage">HtmlUnit test</a> by using the Page Object
Pattern. As mentioned previously, we can use the Page Object Pattern with HtmlUnit and
WebDriver, but it is even easier with Geb. Consider our new Groovy-based<code>CreateMessagePage</code> implementation:</p> <div class="language- extra-class"><pre class="language-text"><code>class CreateMessagePage extends Page {
    static url = 'messages/form'
    static at = { assert title == 'Messages : Create'; true }
    static content =  {
        submit { $('input[type=submit]') }
        form { $('form') }
        errors(required:false) { $('label.error, .alert-error')?.text() }
    }
}
</code></pre></div><p>Our <code>CreateMessagePage</code> extends <code>Page</code>. We do not go over the details of <code>Page</code>, but, in
summary, it contains common functionality for all of our pages. We define a URL in which
this page can be found. This lets us navigate to the page, as follows:</p> <div class="language- extra-class"><pre class="language-text"><code>to CreateMessagePage
</code></pre></div><p>We also have an <code>at</code> closure that determines if we are at the specified page. It should
return <code>true</code> if we are on the correct page. This is why we can assert that we are on the
correct page, as follows:</p> <div class="language- extra-class"><pre class="language-text"><code>then:
at CreateMessagePage
errors.contains('This field is required.')
</code></pre></div><table><thead><tr><th></th> <th>We use an assertion in the closure so that we can determine where things went wrong<br>if we were at the wrong page.</th></tr></thead> <tbody></tbody></table> <p>Next, we create a <code>content</code> closure that specifies all the areas of interest within the
page. We can use a<a href="http://www.gebish.org/manual/current/#the-jquery-ish-navigator-api" target="_blank" rel="noopener noreferrer">jQuery-ish Navigator
API<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> to select the content in which we are interested.</p> <p>Finally, we can verify that a new message was created successfully, as follows:</p> <div class="language- extra-class"><pre class="language-text"><code>then:
at ViewMessagePage
success == 'Successfully created a new message'
id
date
summary == expectedSummary
message == expectedMessage
</code></pre></div><p>For further details on how to get the most out of Geb, see<a href="http://www.gebish.org/manual/current/" target="_blank" rel="noopener noreferrer">The Book of Geb<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> user’s manual.</p> <h3 id="_3-8-testing-client-applications"><a href="#_3-8-testing-client-applications" class="header-anchor">#</a> 3.8. Testing Client Applications</h3> <p>You can use client-side tests to test code that internally uses the <code>RestTemplate</code>. The
idea is to declare expected requests and to provide “stub” responses so that you can
focus on testing the code in isolation (that is, without running a server). The following
example shows how to do so:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>RestTemplate restTemplate = new RestTemplate();

MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();
mockServer.expect(requestTo(&quot;/greeting&quot;)).andRespond(withSuccess());

// Test code that uses the above RestTemplate ...

mockServer.verify();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val restTemplate = RestTemplate()

val mockServer = MockRestServiceServer.bindTo(restTemplate).build()
mockServer.expect(requestTo(&quot;/greeting&quot;)).andRespond(withSuccess())

// Test code that uses the above RestTemplate ...

mockServer.verify()
</code></pre></div><p>In the preceding example, <code>MockRestServiceServer</code> (the central class for client-side REST
tests) configures the <code>RestTemplate</code> with a custom <code>ClientHttpRequestFactory</code> that
asserts actual requests against expectations and returns “stub” responses. In this
case, we expect a request to <code>/greeting</code> and want to return a 200 response with<code>text/plain</code> content. We can define additional expected requests and stub responses as
needed. When we define expected requests and stub responses, the <code>RestTemplate</code> can be
used in client-side code as usual. At the end of testing, <code>mockServer.verify()</code> can be
used to verify that all expectations have been satisfied.</p> <p>By default, requests are expected in the order in which expectations were declared. You
can set the <code>ignoreExpectOrder</code> option when building the server, in which case all
expectations are checked (in order) to find a match for a given request. That means
requests are allowed to come in any order. The following example uses <code>ignoreExpectOrder</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>server = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>server = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build()
</code></pre></div><p>Even with unordered requests by default, each request is allowed to run once only.
The <code>expect</code> method provides an overloaded variant that accepts an <code>ExpectedCount</code>argument that specifies a count range (for example, <code>once</code>, <code>manyTimes</code>, <code>max</code>, <code>min</code>,<code>between</code>, and so on). The following example uses <code>times</code>:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>RestTemplate restTemplate = new RestTemplate();

MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();
mockServer.expect(times(2), requestTo(&quot;/something&quot;)).andRespond(withSuccess());
mockServer.expect(times(3), requestTo(&quot;/somewhere&quot;)).andRespond(withSuccess());

// ...

mockServer.verify();
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val restTemplate = RestTemplate()

val mockServer = MockRestServiceServer.bindTo(restTemplate).build()
mockServer.expect(times(2), requestTo(&quot;/something&quot;)).andRespond(withSuccess())
mockServer.expect(times(3), requestTo(&quot;/somewhere&quot;)).andRespond(withSuccess())

// ...

mockServer.verify()
</code></pre></div><p>Note that, when <code>ignoreExpectOrder</code> is not set (the default), and, therefore, requests
are expected in order of declaration, then that order applies only to the first of any
expected request. For example if &quot;/something&quot; is expected two times followed by
&quot;/somewhere&quot; three times, then there should be a request to &quot;/something&quot; before there is
a request to &quot;/somewhere&quot;, but, aside from that subsequent &quot;/something&quot; and &quot;/somewhere&quot;,
requests can come at any time.</p> <p>As an alternative to all of the above, the client-side test support also provides a<code>ClientHttpRequestFactory</code> implementation that you can configure into a <code>RestTemplate</code> to
bind it to a <code>MockMvc</code> instance. That allows processing requests using actual server-side
logic but without running a server. The following example shows how to do so:</p> <p>Java</p> <div class="language- extra-class"><pre class="language-text"><code>MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
this.restTemplate = new RestTemplate(new MockMvcClientHttpRequestFactory(mockMvc));

// Test code that uses the above RestTemplate ...
</code></pre></div><p>Kotlin</p> <div class="language- extra-class"><pre class="language-text"><code>val mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build()
restTemplate = RestTemplate(MockMvcClientHttpRequestFactory(mockMvc))

// Test code that uses the above RestTemplate ...
</code></pre></div><h4 id="_3-8-1-static-imports"><a href="#_3-8-1-static-imports" class="header-anchor">#</a> 3.8.1. Static Imports</h4> <p>As with server-side tests, the fluent API for client-side tests requires a few static
imports. Those are easy to find by searching for <code>MockRest*</code>. Eclipse users should add<code>MockRestRequestMatchers.*</code> and <code>MockRestResponseCreators.*</code> as
“favorite static members” in the Eclipse preferences under Java → Editor → Content
Assist → Favorites. That allows using content assist after typing the first character of
the static method name. Other IDEs (such IntelliJ) may not require any additional
configuration. Check for the support for code completion on static members.</p> <h4 id="_3-8-2-further-examples-of-client-side-rest-tests"><a href="#_3-8-2-further-examples-of-client-side-rest-tests" class="header-anchor">#</a> 3.8.2. Further Examples of Client-side REST Tests</h4> <p>Spring MVC Test’s own tests include<a href="https://github.com/spring-projects/spring-framework/tree/main/spring-test/src/test/java/org/springframework/test/web/client/samples" target="_blank" rel="noopener noreferrer">example
tests<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> of client-side REST tests.</p> <h2 id="_4-further-resources"><a href="#_4-further-resources" class="header-anchor">#</a> 4. Further Resources</h2> <p>See the following resources for more information about testing:</p> <ul><li><p><a href="https://www.junit.org/" target="_blank" rel="noopener noreferrer">JUnit<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>: “A programmer-friendly testing framework for Java”.
Used by the Spring Framework in its test suite and supported in the<a href="#testcontext-framework">Spring TestContext Framework</a>.</p></li> <li><p><a href="https://testng.org/" target="_blank" rel="noopener noreferrer">TestNG<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>: A testing framework inspired by JUnit with added support
for test groups, data-driven testing, distributed testing, and other features. Supported
in the <a href="#testcontext-framework">Spring TestContext Framework</a></p></li> <li><p><a href="https://assertj.github.io/doc/" target="_blank" rel="noopener noreferrer">AssertJ<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>: “Fluent assertions for Java”,
including support for Java 8 lambdas, streams, and other features.</p></li> <li><p><a href="https://en.wikipedia.org/wiki/Mock_Object" target="_blank" rel="noopener noreferrer">Mock Objects<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>: Article in Wikipedia.</p></li> <li><p><a href="http://www.mockobjects.com/" target="_blank" rel="noopener noreferrer">MockObjects.com<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>: Web site dedicated to mock objects, a
technique for improving the design of code within test-driven development.</p></li> <li><p><a href="https://mockito.github.io" target="_blank" rel="noopener noreferrer">Mockito<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>: Java mock library based on the<a href="http://xunitpatterns.com/Test%20Spy.html" target="_blank" rel="noopener noreferrer">Test Spy<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> pattern. Used by the Spring Framework
in its test suite.</p></li> <li><p><a href="https://easymock.org/" target="_blank" rel="noopener noreferrer">EasyMock<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>: Java library “that provides Mock Objects for
interfaces (and objects through the class extension) by generating them on the fly using
Java’s proxy mechanism.”</p></li> <li><p><a href="https://jmock.org/" target="_blank" rel="noopener noreferrer">JMock<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>: Library that supports test-driven development of Java code
with mock objects.</p></li> <li><p><a href="https://www.dbunit.org/" target="_blank" rel="noopener noreferrer">DbUnit<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>: JUnit extension (also usable with Ant and Maven) that
is targeted at database-driven projects and, among other things, puts your database into
a known state between test runs.</p></li> <li><p><a href="https://www.testcontainers.org/" target="_blank" rel="noopener noreferrer">Testcontainers<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>: Java library that supports JUnit
tests, providing lightweight, throwaway instances of common databases, Selenium web
browsers, or anything else that can run in a Docker container.</p></li> <li><p><a href="https://sourceforge.net/projects/grinder/" target="_blank" rel="noopener noreferrer">The Grinder<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>: Java load testing framework.</p></li> <li><p><a href="https://github.com/Ninja-Squad/springmockk" target="_blank" rel="noopener noreferrer">SpringMockK<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>: Support for Spring Boot
integration tests written in Kotlin using <a href="https://mockk.io/" target="_blank" rel="noopener noreferrer">MockK<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a> instead of Mockito.</p></li></ul></div> <footer class="page-edit"><div class="edit-link"><a href="https://gitcode.net/dev-cloud/spring-docs/-/blob/master/docs/en/spring-framework/testing.md" target="_blank" rel="noopener noreferrer">Edit this page on GitCode</a> <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></div> <div class="last-updated"><span class="prefix">Last Updated:</span> <span class="time">Thu Mar 17 2022 18:19:53 GMT+0800</span></div></footer> <div class="page-nav"><p class="inner"><span class="prev">

      <a href="/en/spring-framework/core.html" class="prev">
        Core Technologies
      </a></span> <span class="next"><a href="/en/spring-framework/data-access.html">
        Data Access
      </a>

    </span></p></div> </main></div><div class="global-ui"></div></div>
    <script src="/assets/js/app.cf11b18e.js" defer></script><script src="/assets/js/3.50918073.js" defer></script><script src="/assets/js/4.cd4c3ff4.js" defer></script><script src="/assets/js/99.513483d0.js" defer></script>
  </body>
</html>