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
|
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Web.Mvc.Async;
using System.Web.Profile;
using System.Web.Routing;
using System.Web.TestUtil;
using Microsoft.Web.UnitTestUtil;
using Moq;
using Moq.Protected;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Mvc.Test
{
public class ControllerTest
{
[Fact]
public void ActionInvokerProperty()
{
// Arrange
Controller controller = new EmptyController();
// Act & Assert
MemberHelper.TestPropertyWithDefaultInstance(controller, "ActionInvoker", new ControllerActionInvoker());
}
[Fact]
public void ContentWithContentString()
{
// Arrange
Controller controller = new EmptyController();
string content = "Some content";
// Act
ContentResult result = controller.Content(content);
// Assert
Assert.Equal(content, result.Content);
}
[Fact]
public void ContentWithContentStringAndContentType()
{
// Arrange
Controller controller = new EmptyController();
string content = "Some content";
string contentType = "Some content type";
// Act
ContentResult result = controller.Content(content, contentType);
// Assert
Assert.Equal(content, result.Content);
Assert.Equal(contentType, result.ContentType);
}
[Fact]
public void ContentWithContentStringAndContentTypeAndEncoding()
{
// Arrange
Controller controller = new EmptyController();
string content = "Some content";
string contentType = "Some content type";
Encoding contentEncoding = Encoding.UTF8;
// Act
ContentResult result = controller.Content(content, contentType, contentEncoding);
// Assert
Assert.Equal(content, result.Content);
Assert.Equal(contentType, result.ContentType);
Assert.Same(contentEncoding, result.ContentEncoding);
}
[Fact]
public void ContextProperty()
{
var controller = new EmptyController();
MemberHelper.TestPropertyValue(controller, "ControllerContext", new Mock<ControllerContext>().Object);
}
[Fact]
public void HttpContextProperty()
{
var c = new EmptyController();
Assert.Null(c.HttpContext);
Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(cc => cc.Controller).Returns(c);
mockControllerContext.Setup(cc => cc.HttpContext).Returns(mockHttpContext.Object);
c.ControllerContext = mockControllerContext.Object;
Assert.Equal(mockHttpContext.Object, c.HttpContext);
}
[Fact]
public void HttpNotFound()
{
// Arrange
var c = new EmptyController();
// Act
HttpNotFoundResult result = c.HttpNotFound();
// Assert
Assert.NotNull(result);
Assert.Null(result.StatusDescription);
Assert.Equal(404, result.StatusCode);
}
[Fact]
public void HttpNotFoundWithNullStatusDescription()
{
// Arrange
var c = new EmptyController();
// Act
HttpNotFoundResult result = c.HttpNotFound(statusDescription: null);
// Assert
Assert.NotNull(result);
Assert.Null(result.StatusDescription);
Assert.Equal(404, result.StatusCode);
}
[Fact]
public void HttpNotFoundWithStatusDescription()
{
// Arrange
var c = new EmptyController();
// Act
HttpNotFoundResult result = c.HttpNotFound(statusDescription: "I lost it");
// Assert
Assert.NotNull(result);
Assert.Equal("I lost it", result.StatusDescription);
Assert.Equal(404, result.StatusCode);
}
[Fact]
public void ModelStateProperty()
{
// Arrange
Controller controller = new EmptyController();
// Act & assert
Assert.Same(controller.ViewData.ModelState, controller.ModelState);
}
[Fact]
public void ProfileProperty()
{
var c = new EmptyController();
Assert.Null(c.Profile);
Mock<ProfileBase> mockProfile = new Mock<ProfileBase>();
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(cc => cc.Controller).Returns(c);
mockControllerContext.Setup(cc => cc.HttpContext.Profile).Returns(mockProfile.Object);
c.ControllerContext = mockControllerContext.Object;
Assert.Equal(mockProfile.Object, c.Profile);
}
[Fact]
public void RequestProperty()
{
var c = new EmptyController();
Assert.Null(c.Request);
Mock<HttpRequestBase> mockHttpRequest = new Mock<HttpRequestBase>();
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(cc => cc.Controller).Returns(c);
mockControllerContext.Setup(cc => cc.HttpContext.Request).Returns(mockHttpRequest.Object);
c.ControllerContext = mockControllerContext.Object;
Assert.Equal(mockHttpRequest.Object, c.Request);
}
[Fact]
public void ResponseProperty()
{
var c = new EmptyController();
Assert.Null(c.Request);
Mock<HttpResponseBase> mockHttpResponse = new Mock<HttpResponseBase>();
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(cc => cc.Controller).Returns(c);
mockControllerContext.Setup(cc => cc.HttpContext.Response).Returns(mockHttpResponse.Object);
c.ControllerContext = mockControllerContext.Object;
Assert.Equal(mockHttpResponse.Object, c.Response);
}
[Fact]
public void ServerProperty()
{
var c = new EmptyController();
Assert.Null(c.Request);
Mock<HttpServerUtilityBase> mockServerUtility = new Mock<HttpServerUtilityBase>();
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(cc => cc.Controller).Returns(c);
mockControllerContext.Setup(cc => cc.HttpContext.Server).Returns(mockServerUtility.Object);
c.ControllerContext = mockControllerContext.Object;
Assert.Equal(mockServerUtility.Object, c.Server);
}
[Fact]
public void SessionProperty()
{
var c = new EmptyController();
Assert.Null(c.Request);
Mock<HttpSessionStateBase> mockSessionState = new Mock<HttpSessionStateBase>();
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(cc => cc.Controller).Returns(c);
mockControllerContext.Setup(cc => cc.HttpContext.Session).Returns(mockSessionState.Object);
c.ControllerContext = mockControllerContext.Object;
Assert.Same(mockSessionState.Object, c.Session);
}
[Fact]
public void UrlProperty()
{
// Arrange
EmptyController controller = new EmptyController();
RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());
// Act
controller.PublicInitialize(requestContext);
// Assert
Assert.NotNull(controller.Url);
}
[Fact]
public void UserProperty()
{
var c = new EmptyController();
Assert.Null(c.Request);
Mock<IPrincipal> mockUser = new Mock<IPrincipal>();
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(cc => cc.Controller).Returns(c);
mockControllerContext.Setup(cc => cc.HttpContext.User).Returns(mockUser.Object);
c.ControllerContext = mockControllerContext.Object;
Assert.Equal(mockUser.Object, c.User);
}
[Fact]
public void RouteDataProperty()
{
var c = new EmptyController();
Assert.Null(c.Request);
RouteData rd = new RouteData();
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(cc => cc.Controller).Returns(c);
mockControllerContext.Setup(cc => cc.RouteData).Returns(rd);
c.ControllerContext = mockControllerContext.Object;
Assert.Equal(rd, c.RouteData);
}
[Fact]
public void ControllerMethodsDoNotHaveNonActionAttribute()
{
var methods = typeof(Controller).GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var method in methods)
{
var attrs = method.GetCustomAttributes(typeof(NonActionAttribute), true /* inherit */);
Assert.True(attrs.Length == 0, "Methods on the Controller class should not be marked [NonAction]: " + method);
}
}
[Fact]
public void DisposeCallsProtectedDisposingMethod()
{
// Arrange
Mock<Controller> mockController = new Mock<Controller>();
mockController.Protected().Setup("Dispose", true).Verifiable();
Controller controller = mockController.Object;
// Act
controller.Dispose();
// Assert
mockController.Verify();
}
[Fact]
public void ExecuteWithUnknownAction()
{
// Arrange
UnknownActionController controller = new UnknownActionController();
// We need a provider since Controller.Execute is called
controller.TempDataProvider = new EmptyTempDataProvider();
ControllerContext context = GetControllerContext("Foo");
Mock<IActionInvoker> mockInvoker = new Mock<IActionInvoker>();
mockInvoker.Setup(o => o.InvokeAction(context, "Foo")).Returns(false);
controller.ActionInvoker = mockInvoker.Object;
// Act
((IController)controller).Execute(context.RequestContext);
// Assert
Assert.True(controller.WasCalled);
}
[Fact]
public void FileWithContents()
{
// Arrange
EmptyController controller = new EmptyController();
byte[] fileContents = new byte[0];
// Act
FileContentResult result = controller.File(fileContents, "someContentType");
// Assert
Assert.NotNull(result);
Assert.Same(fileContents, result.FileContents);
Assert.Equal("someContentType", result.ContentType);
Assert.Equal(String.Empty, result.FileDownloadName);
}
[Fact]
public void FileWithContentsAndFileDownloadName()
{
// Arrange
EmptyController controller = new EmptyController();
byte[] fileContents = new byte[0];
// Act
FileContentResult result = controller.File(fileContents, "someContentType", "someDownloadName");
// Assert
Assert.NotNull(result);
Assert.Same(fileContents, result.FileContents);
Assert.Equal("someContentType", result.ContentType);
Assert.Equal("someDownloadName", result.FileDownloadName);
}
[Fact]
public void FileWithPath()
{
// Arrange
EmptyController controller = new EmptyController();
// Act
FilePathResult result = controller.File("somePath", "someContentType");
// Assert
Assert.NotNull(result);
Assert.Equal("somePath", result.FileName);
Assert.Equal("someContentType", result.ContentType);
Assert.Equal(String.Empty, result.FileDownloadName);
}
[Fact]
public void FileWithPathAndFileDownloadName()
{
// Arrange
EmptyController controller = new EmptyController();
// Act
FilePathResult result = controller.File("somePath", "someContentType", "someDownloadName");
// Assert
Assert.NotNull(result);
Assert.Equal("somePath", result.FileName);
Assert.Equal("someContentType", result.ContentType);
Assert.Equal("someDownloadName", result.FileDownloadName);
}
[Fact]
public void FileWithStream()
{
// Arrange
EmptyController controller = new EmptyController();
Stream fileStream = Stream.Null;
// Act
FileStreamResult result = controller.File(fileStream, "someContentType");
// Assert
Assert.NotNull(result);
Assert.Same(fileStream, result.FileStream);
Assert.Equal("someContentType", result.ContentType);
Assert.Equal(String.Empty, result.FileDownloadName);
}
[Fact]
public void FileWithStreamAndFileDownloadName()
{
// Arrange
EmptyController controller = new EmptyController();
Stream fileStream = Stream.Null;
// Act
FileStreamResult result = controller.File(fileStream, "someContentType", "someDownloadName");
// Assert
Assert.NotNull(result);
Assert.Same(fileStream, result.FileStream);
Assert.Equal("someContentType", result.ContentType);
Assert.Equal("someDownloadName", result.FileDownloadName);
}
[Fact]
public void HandleUnknownActionThrows()
{
var controller = new EmptyController();
Assert.Throws<HttpException>(
delegate { controller.HandleUnknownAction("UnknownAction"); },
"A public action method 'UnknownAction' was not found on controller 'System.Web.Mvc.Test.ControllerTest+EmptyController'.");
}
[Fact]
public void JavaScript()
{
// Arrange
Controller controller = GetEmptyController();
string script = "alert('foo');";
// Act
JavaScriptResult result = controller.JavaScript(script);
// Assert
Assert.Equal(script, result.Script);
}
[Fact]
public void PartialView()
{
// Arrange
Controller controller = GetEmptyController();
// Act
PartialViewResult result = controller.PartialView();
// Assert
Assert.Same(controller.TempData, result.TempData);
Assert.Same(controller.ViewData, result.ViewData);
Assert.Same(ViewEngines.Engines, result.ViewEngineCollection);
}
[Fact]
public void PartialView_Model()
{
// Arrange
Controller controller = GetEmptyController();
object model = new object();
// Act
PartialViewResult result = controller.PartialView(model);
// Assert
Assert.Same(model, result.ViewData.Model);
Assert.Same(controller.TempData, result.TempData);
Assert.Same(controller.ViewData, result.ViewData);
}
[Fact]
public void PartialView_ViewName()
{
// Arrange
Controller controller = GetEmptyController();
// Act
PartialViewResult result = controller.PartialView("Some partial view");
// Assert
Assert.Equal("Some partial view", result.ViewName);
Assert.Same(controller.TempData, result.TempData);
Assert.Same(controller.ViewData, result.ViewData);
}
[Fact]
public void PartialView_ViewName_Model()
{
// Arrange
Controller controller = GetEmptyController();
object model = new object();
// Act
PartialViewResult result = controller.PartialView("Some partial view", model);
// Assert
Assert.Equal("Some partial view", result.ViewName);
Assert.Same(model, result.ViewData.Model);
Assert.Same(controller.TempData, result.TempData);
Assert.Same(controller.ViewData, result.ViewData);
}
[Fact]
public void PartialView_ViewEngineCollection()
{
// Arrange
Controller controller = GetEmptyController();
ViewEngineCollection viewEngines = new ViewEngineCollection();
controller.ViewEngineCollection = viewEngines;
// Act
PartialViewResult result = controller.PartialView();
// Assert
Assert.Same(viewEngines, result.ViewEngineCollection);
}
[Fact]
public void RedirectToActionClonesRouteValueDictionary()
{
// The RedirectToAction() method should clone the provided dictionary, then operate on the clone.
// The original dictionary should remain unmodified throughout the helper's execution.
// Arrange
Controller controller = GetEmptyController();
RouteValueDictionary values = new RouteValueDictionary(new { Action = "SomeAction", Controller = "SomeController" });
// Act
controller.RedirectToAction("SomeOtherAction", "SomeOtherController", values);
// Assert
Assert.Equal(2, values.Count);
Assert.Equal("SomeAction", values["action"]);
Assert.Equal("SomeController", values["controller"]);
}
[Fact]
public void RedirectToActionOverwritesActionDictionaryKey()
{
// Arrange
Controller controller = GetEmptyController();
object values = new { Action = "SomeAction" };
// Act
RedirectToRouteResult result = controller.RedirectToAction("SomeOtherAction", values);
RouteValueDictionary newValues = result.RouteValues;
// Assert
Assert.Equal("SomeOtherAction", newValues["action"]);
}
[Fact]
public void RedirectToActionOverwritesControllerDictionaryKeyIfSpecified()
{
// Arrange
Controller controller = GetEmptyController();
object values = new { Action = "SomeAction", Controller = "SomeController" };
// Act
RedirectToRouteResult result = controller.RedirectToAction("SomeOtherAction", "SomeOtherController", values);
RouteValueDictionary newValues = result.RouteValues;
// Assert
Assert.Equal("SomeOtherController", newValues["controller"]);
}
[Fact]
public void RedirectToActionPreservesControllerDictionaryKeyIfNotSpecified()
{
// Arrange
Controller controller = GetEmptyController();
object values = new { Controller = "SomeController" };
// Act
RedirectToRouteResult result = controller.RedirectToAction("SomeOtherAction", values);
RouteValueDictionary newValues = result.RouteValues;
// Assert
Assert.Equal("SomeController", newValues["controller"]);
}
[Fact]
public void RedirectToActionWithActionName()
{
// Arrange
Controller controller = GetEmptyController();
// Act
RedirectToRouteResult result = controller.RedirectToAction("SomeOtherAction");
// Assert
Assert.Equal("", result.RouteName);
Assert.Equal("SomeOtherAction", result.RouteValues["action"]);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToActionWithActionNameAndControllerName()
{
// Arrange
Controller controller = GetEmptyController();
// Act
RedirectToRouteResult result = controller.RedirectToAction("SomeOtherAction", "SomeOtherController");
// Assert
Assert.Equal("", result.RouteName);
Assert.Equal("SomeOtherAction", result.RouteValues["action"]);
Assert.Equal("SomeOtherController", result.RouteValues["controller"]);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToActionWithActionNameAndControllerNameAndValuesDictionary()
{
// Arrange
Controller controller = GetEmptyController();
RouteValueDictionary values = new RouteValueDictionary(new { Foo = "SomeFoo" });
// Act
RedirectToRouteResult result = controller.RedirectToAction("SomeOtherAction", "SomeOtherController", values);
// Assert
Assert.Equal("", result.RouteName);
Assert.Equal("SomeOtherAction", result.RouteValues["action"]);
Assert.Equal("SomeOtherController", result.RouteValues["controller"]);
Assert.Equal("SomeFoo", result.RouteValues["foo"]);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToActionWithActionNameAndControllerNameAndValuesObject()
{
// Arrange
Controller controller = GetEmptyController();
object values = new { Foo = "SomeFoo" };
// Act
RedirectToRouteResult result = controller.RedirectToAction("SomeOtherAction", "SomeOtherController", values);
// Assert
Assert.Equal("", result.RouteName);
Assert.Equal("SomeOtherAction", result.RouteValues["action"]);
Assert.Equal("SomeOtherController", result.RouteValues["controller"]);
Assert.Equal("SomeFoo", result.RouteValues["foo"]);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToActionSelectsCurrentControllerByDefault()
{
// Arrange
TestRouteController controller = new TestRouteController();
controller.ControllerContext = GetControllerContext("SomeAction", "TestRoute");
// Act
RedirectToRouteResult route = controller.Index() as RedirectToRouteResult;
// Assert
Assert.Equal("SomeAction", route.RouteValues["action"]);
Assert.Equal("TestRoute", route.RouteValues["controller"]);
}
[Fact]
public void RedirectToActionDictionaryOverridesDefaultControllerName()
{
// Arrange
TestRouteController controller = new TestRouteController();
object values = new { controller = "SomeOtherController" };
controller.ControllerContext = GetControllerContext("SomeAction", "TestRoute");
// Act
RedirectToRouteResult route = controller.RedirectToAction("SomeOtherAction", values);
// Assert
Assert.Equal("SomeOtherAction", route.RouteValues["action"]);
Assert.Equal("SomeOtherController", route.RouteValues["controller"]);
}
[Fact]
public void RedirectToActionSimpleOverridesCallLegacyMethod()
{
// The simple overrides need to call RedirectToAction(string, string, RouteValueDictionary) to maintain backwards compat
// Arrange
int invocationCount = 0;
Mock<Controller> controllerMock = new Mock<Controller>();
controllerMock.Setup(c => c.RedirectToAction(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<RouteValueDictionary>())).Callback(() => { invocationCount++; });
Controller controller = controllerMock.Object;
// Act
controller.RedirectToAction("SomeAction");
controller.RedirectToAction("SomeAction", (object)null);
controller.RedirectToAction("SomeAction", (RouteValueDictionary)null);
controller.RedirectToAction("SomeAction", "SomeController");
controller.RedirectToAction("SomeAction", "SomeController", (object)null);
// Assert
Assert.Equal(5, invocationCount);
}
[Fact]
public void RedirectToActionWithActionNameAndValuesDictionary()
{
// Arrange
Controller controller = GetEmptyController();
RouteValueDictionary values = new RouteValueDictionary(new { Foo = "SomeFoo" });
// Act
RedirectToRouteResult result = controller.RedirectToAction("SomeOtherAction", values);
// Assert
Assert.Equal("", result.RouteName);
Assert.Equal("SomeOtherAction", result.RouteValues["action"]);
Assert.Equal("SomeFoo", result.RouteValues["foo"]);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToActionWithActionNameAndValuesObject()
{
// Arrange
Controller controller = GetEmptyController();
object values = new { Foo = "SomeFoo" };
// Act
RedirectToRouteResult result = controller.RedirectToAction("SomeOtherAction", values);
// Assert
Assert.Equal("", result.RouteName);
Assert.Equal("SomeOtherAction", result.RouteValues["action"]);
Assert.Equal("SomeFoo", result.RouteValues["foo"]);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToActionWithNullRouteValueDictionary()
{
// Arrange
Controller controller = GetEmptyController();
// Act
RedirectToRouteResult result = controller.RedirectToAction("SomeOtherAction", (RouteValueDictionary)null);
RouteValueDictionary newValues = result.RouteValues;
// Assert
Assert.Single(newValues);
Assert.Equal("SomeOtherAction", newValues["action"]);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToActionPermanent()
{
// Arrange
Controller controller = GetEmptyController();
// Act
RedirectToRouteResult result = controller.RedirectToActionPermanent("SomeOtherAction");
// Assert
Assert.True(result.Permanent);
Assert.Equal("SomeOtherAction", result.RouteValues["action"]);
Assert.Null(result.RouteValues["controller"]);
}
[Fact]
public void RedirectToActionPermanentWithObjectDictionary()
{
// Arrange
Controller controller = GetEmptyController();
// Act
RedirectToRouteResult result = controller.RedirectToActionPermanent("SomeOtherAction", controllerName: "SomeController", routeValues: new { foo = "bar" });
// Assert
Assert.True(result.Permanent);
Assert.Equal("SomeOtherAction", result.RouteValues["action"]);
Assert.Equal("bar", result.RouteValues["foo"]);
Assert.Equal("SomeController", result.RouteValues["controller"]);
}
[Fact]
public void RedirectToActionPermanentWithRouteValueDictionary()
{
// Arrange
Controller controller = GetEmptyController();
// Act
RedirectToRouteResult result = controller.RedirectToActionPermanent("SomeOtherAction", routeValues: new RouteValueDictionary(new { foo = "bar" }));
// Assert
Assert.True(result.Permanent);
Assert.Equal("SomeOtherAction", result.RouteValues["action"]);
Assert.Equal("bar", result.RouteValues["foo"]);
}
[Fact]
public void RedirectToRouteSimpleOverridesCallLegacyMethod()
{
// The simple overrides need to call RedirectToRoute(string, RouteValueDictionary) to maintain backwards compat
// Arrange
int invocationCount = 0;
Mock<Controller> controllerMock = new Mock<Controller>();
controllerMock.Setup(c => c.RedirectToRoute(It.IsAny<string>(), It.IsAny<RouteValueDictionary>())).Callback(() => { invocationCount++; });
Controller controller = controllerMock.Object;
// Act
controller.RedirectToRoute("SomeRoute");
controller.RedirectToRoute("SomeRoute", (object)null);
controller.RedirectToRoute((object)null);
controller.RedirectToRoute((RouteValueDictionary)null);
// Assert
Assert.Equal(4, invocationCount);
}
[Fact]
public void RedirectToRouteWithNullRouteValueDictionary()
{
// Arrange
Controller controller = GetEmptyController();
// Act
RedirectToRouteResult result = controller.RedirectToRoute((RouteValueDictionary)null);
// Assert
Assert.Empty(result.RouteValues);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToRouteWithObjectDictionary()
{
// Arrange
Controller controller = GetEmptyController();
var values = new { Foo = "MyFoo" };
// Act
RedirectToRouteResult result = controller.RedirectToRoute(values);
// Assert
Assert.Single(result.RouteValues);
Assert.Equal("MyFoo", result.RouteValues["Foo"]);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToRouteWithRouteValueDictionary()
{
// Arrange
Controller controller = GetEmptyController();
RouteValueDictionary values = new RouteValueDictionary() { { "Foo", "MyFoo" } };
// Act
RedirectToRouteResult result = controller.RedirectToRoute(values);
// Assert
Assert.Single(result.RouteValues);
Assert.Equal("MyFoo", result.RouteValues["Foo"]);
Assert.NotSame(values, result.RouteValues);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToRouteWithName()
{
// Arrange
Controller controller = GetEmptyController();
// Act
RedirectToRouteResult result = controller.RedirectToRoute("foo");
// Assert
Assert.Empty(result.RouteValues);
Assert.Equal("foo", result.RouteName);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToRouteWithNameAndNullRouteValueDictionary()
{
// Arrange
Controller controller = GetEmptyController();
// Act
RedirectToRouteResult result = controller.RedirectToRoute("foo", (RouteValueDictionary)null);
// Assert
Assert.Empty(result.RouteValues);
Assert.Equal("foo", result.RouteName);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToRouteWithNullNameAndNullRouteValueDictionary()
{
// Arrange
Controller controller = GetEmptyController();
// Act
RedirectToRouteResult result = controller.RedirectToRoute(null, (RouteValueDictionary)null);
// Assert
Assert.Empty(result.RouteValues);
Assert.Equal(String.Empty, result.RouteName);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToRouteWithNameAndObjectDictionary()
{
// Arrange
Controller controller = GetEmptyController();
var values = new { Foo = "MyFoo" };
// Act
RedirectToRouteResult result = controller.RedirectToRoute("foo", values);
// Assert
Assert.Single(result.RouteValues);
Assert.Equal("MyFoo", result.RouteValues["Foo"]);
Assert.Equal("foo", result.RouteName);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToRouteWithNameAndRouteValueDictionary()
{
// Arrange
Controller controller = GetEmptyController();
RouteValueDictionary values = new RouteValueDictionary() { { "Foo", "MyFoo" } };
// Act
RedirectToRouteResult result = controller.RedirectToRoute("foo", values);
// Assert
Assert.Single(result.RouteValues);
Assert.Equal("MyFoo", result.RouteValues["Foo"]);
Assert.NotSame(values, result.RouteValues);
Assert.Equal("foo", result.RouteName);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectToRoutePermanentWithObjectDictionary()
{
// Arrange
Controller controller = GetEmptyController();
// Act
RedirectToRouteResult result = controller.RedirectToRoutePermanent(routeValues: new { Foo = "Bar" });
// Assert
Assert.True(result.Permanent);
Assert.Equal("Bar", result.RouteValues["Foo"]);
}
[Fact]
public void RedirectToRoutePermanentWithRouteValueDictionary()
{
// Arrange
Controller controller = GetEmptyController();
// Act
RedirectToRouteResult result = controller.RedirectToRoutePermanent(routeValues: new RouteValueDictionary(new { Foo = "Bar" }));
// Assert
Assert.True(result.Permanent);
Assert.Equal("Bar", result.RouteValues["Foo"]);
}
[Fact]
public void RedirectReturnsCorrectActionResult()
{
// Arrange
Controller controller = GetEmptyController();
// Act & Assert
var result = controller.Redirect("http://www.contoso.com/");
// Assert
Assert.Equal("http://www.contoso.com/", result.Url);
Assert.False(result.Permanent);
}
[Fact]
public void RedirectPermanentReturnsCorrectActionResult()
{
// Arrange
Controller controller = GetEmptyController();
// Act & Assert
var result = controller.RedirectPermanent("http://www.contoso.com/");
// Assert
Assert.Equal("http://www.contoso.com/", result.Url);
Assert.True(result.Permanent);
}
[Fact]
public void RedirectWithEmptyUrlThrows()
{
// Arrange
Controller controller = GetEmptyController();
// Act & Assert
Assert.ThrowsArgumentNullOrEmpty(
delegate { controller.Redirect(String.Empty); },
"url");
}
[Fact]
public void RedirectPermanentWithEmptyUrlThrows()
{
// Arrange
Controller controller = GetEmptyController();
// Act & Assert
Assert.ThrowsArgumentNullOrEmpty(
delegate { controller.RedirectPermanent(String.Empty); },
"url");
}
[Fact]
public void RedirectWithNullUrlThrows()
{
// Arrange
Controller controller = GetEmptyController();
// Act & Assert
Assert.ThrowsArgumentNullOrEmpty(
delegate { controller.Redirect(url: null); },
"url");
}
[Fact]
public void RedirectPermanentWithNullUrlThrows()
{
// Arrange
Controller controller = GetEmptyController();
// Act & Assert
Assert.ThrowsArgumentNullOrEmpty(
delegate { controller.RedirectPermanent(url: null); },
"url");
}
[Fact]
public void View()
{
// Arrange
Controller controller = GetEmptyController();
// Act
ViewResult result = controller.View();
// Assert
Assert.Same(controller.ViewData, result.ViewData);
Assert.Same(controller.TempData, result.TempData);
Assert.Same(ViewEngines.Engines, result.ViewEngineCollection);
}
[Fact]
public void View_Model()
{
// Arrange
Controller controller = GetEmptyController();
object viewItem = new object();
// Act
ViewResult result = controller.View(viewItem);
// Assert
Assert.Same(viewItem, result.ViewData.Model);
Assert.Same(controller.TempData, result.TempData);
}
[Fact]
public void View_ViewName()
{
// Arrange
Controller controller = GetEmptyController();
// Act
ViewResult result = controller.View("Foo");
// Assert
Assert.Equal("Foo", result.ViewName);
Assert.Same(controller.ViewData, result.ViewData);
Assert.Same(controller.TempData, result.TempData);
}
[Fact]
public void View_ViewName_Model()
{
// Arrange
Controller controller = GetEmptyController();
object viewItem = new object();
// Act
ViewResult result = controller.View("Foo", viewItem);
// Assert
Assert.Equal("Foo", result.ViewName);
Assert.Same(viewItem, result.ViewData.Model);
Assert.Same(controller.TempData, result.TempData);
}
[Fact]
public void View_ViewName_MasterViewName()
{
// Arrange
Controller controller = GetEmptyController();
// Act
ViewResult result = controller.View("Foo", "Bar");
// Assert
Assert.Equal("Foo", result.ViewName);
Assert.Equal("Bar", result.MasterName);
Assert.Same(controller.ViewData, result.ViewData);
Assert.Same(controller.TempData, result.TempData);
}
[Fact]
public void View_ViewName_MasterViewName_Model()
{
// Arrange
Controller controller = GetEmptyController();
object viewItem = new object();
// Act
ViewResult result = controller.View("Foo", "Bar", viewItem);
// Assert
Assert.Equal("Foo", result.ViewName);
Assert.Equal("Bar", result.MasterName);
Assert.Same(viewItem, result.ViewData.Model);
Assert.Same(controller.TempData, result.TempData);
}
[Fact]
public void View_View()
{
// Arrange
Controller controller = GetEmptyController();
IView view = new Mock<IView>().Object;
// Act
ViewResult result = controller.View(view);
// Assert
Assert.Same(result.View, view);
Assert.Same(controller.ViewData, result.ViewData);
Assert.Same(controller.TempData, result.TempData);
}
[Fact]
public void View_View_Model()
{
// Arrange
Controller controller = GetEmptyController();
IView view = new Mock<IView>().Object;
object model = new object();
// Act
ViewResult result = controller.View(view, model);
// Assert
Assert.Same(result.View, view);
Assert.Same(controller.ViewData, result.ViewData);
Assert.Same(controller.TempData, result.TempData);
Assert.Same(model, result.ViewData.Model);
}
[Fact]
public void View_ViewEngineCollection()
{
// Arrange
Controller controller = GetEmptyController();
ViewEngineCollection viewEngines = new ViewEngineCollection();
controller.ViewEngineCollection = viewEngines;
// Act
ViewResult result = controller.View();
// Assert
Assert.Same(viewEngines, result.ViewEngineCollection);
}
internal static void AddRequestParams(Mock<HttpRequestBase> requestMock, object paramValues)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(paramValues);
foreach (PropertyDescriptor prop in props)
{
requestMock.Setup(o => o[It.Is<string>(item => String.Equals(prop.Name, item, StringComparison.OrdinalIgnoreCase))]).Returns((string)prop.GetValue(paramValues));
}
}
[Fact]
public void TempDataGreetUserWithNoUserIDRedirects()
{
// Arrange
TempDataHomeController tempDataHomeController = new TempDataHomeController();
// Act
RedirectToRouteResult result = tempDataHomeController.GreetUser() as RedirectToRouteResult;
RouteValueDictionary values = result.RouteValues;
// Assert
Assert.True(values.ContainsKey("action"));
Assert.Equal("ErrorPage", values["action"]);
Assert.Empty(tempDataHomeController.TempData);
}
[Fact]
public void TempDataGreetUserWithUserIDCopiesToViewDataAndRenders()
{
// Arrange
TempDataHomeController tempDataHomeController = new TempDataHomeController();
tempDataHomeController.TempData["UserID"] = "TestUserID";
// Act
ViewResult result = tempDataHomeController.GreetUser() as ViewResult;
ViewDataDictionary viewData = tempDataHomeController.ViewData;
// Assert
Assert.Equal("GreetUser", result.ViewName);
Assert.NotNull(viewData);
Assert.True(viewData.ContainsKey("NewUserID"));
Assert.Equal("TestUserID", viewData["NewUserID"]);
}
[Fact]
public void TempDataIndexSavesUserIDAndRedirects()
{
// Arrange
TempDataHomeController tempDataHomeController = new TempDataHomeController();
// Act
RedirectToRouteResult result = tempDataHomeController.Index() as RedirectToRouteResult;
RouteValueDictionary values = result.RouteValues;
// Assert
Assert.True(values.ContainsKey("action"));
Assert.Equal("GreetUser", values["action"]);
Assert.True(tempDataHomeController.TempData.ContainsKey("UserID"));
Assert.Equal("user123", tempDataHomeController.TempData["UserID"]);
}
[Fact]
public void TempDataSavedWhenControllerThrows()
{
// Arrange
BrokenController controller = new BrokenController() { ValidateRequest = false };
Mock<HttpContextBase> mockContext = HttpContextHelpers.GetMockHttpContext();
HttpSessionStateBase session = GetEmptySession();
mockContext.Setup(o => o.Session).Returns(session);
RouteData rd = new RouteData();
rd.Values.Add("action", "Crash");
controller.ControllerContext = new ControllerContext(mockContext.Object, rd, controller);
// Assert
Assert.Throws<InvalidOperationException>(
delegate { ((IController)controller).Execute(controller.ControllerContext.RequestContext); });
Assert.NotEqual(mockContext.Object.Session[SessionStateTempDataProvider.TempDataSessionStateKey], null);
TempDataDictionary tempData = new TempDataDictionary();
tempData.Load(controller.ControllerContext, controller.TempDataProvider);
Assert.Equal(tempData["Key1"], "Value1");
}
[Fact]
public void TempDataMovedToPreviousTempDataInDestinationController()
{
// Arrange
Mock<Controller> mockController = new Mock<Controller>() { CallBase = true };
Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();
HttpSessionStateBase session = GetEmptySession();
mockContext.Setup(o => o.Session).Returns(session);
mockController.Object.ControllerContext = new ControllerContext(mockContext.Object, new RouteData(), mockController.Object);
// Act
mockController.Object.TempData.Add("Key", "Value");
mockController.Object.TempData.Save(mockController.Object.ControllerContext, mockController.Object.TempDataProvider);
// Assert
Assert.True(mockController.Object.TempData.ContainsKey("Key"));
Assert.True(mockController.Object.TempData.ContainsValue("Value"));
// Instantiate "destination" controller with the same session state and see that it gets the temp data
Mock<Controller> mockDestinationController = new Mock<Controller>() { CallBase = true };
Mock<HttpContextBase> mockDestinationContext = new Mock<HttpContextBase>();
mockDestinationContext.Setup(o => o.Session).Returns(session);
mockDestinationController.Object.ControllerContext = new ControllerContext(mockDestinationContext.Object, new RouteData(), mockDestinationController.Object);
mockDestinationController.Object.TempData.Load(mockDestinationController.Object.ControllerContext, mockDestinationController.Object.TempDataProvider);
// Assert
Assert.True(mockDestinationController.Object.TempData.ContainsKey("Key"));
// Act
mockDestinationController.Object.TempData["NewKey"] = "NewValue";
Assert.True(mockDestinationController.Object.TempData.ContainsKey("NewKey"));
mockDestinationController.Object.TempData.Save(mockDestinationController.Object.ControllerContext, mockDestinationController.Object.TempDataProvider);
// Instantiate "second destination" controller with the same session state and see that it gets the temp data
Mock<Controller> mockSecondDestinationController = new Mock<Controller>() { CallBase = true };
Mock<HttpContextBase> mockSecondDestinationContext = new Mock<HttpContextBase>();
mockSecondDestinationContext.Setup(o => o.Session).Returns(session);
mockSecondDestinationController.Object.ControllerContext = new ControllerContext(mockSecondDestinationContext.Object, new RouteData(), mockSecondDestinationController.Object);
mockSecondDestinationController.Object.TempData.Load(mockSecondDestinationController.Object.ControllerContext, mockSecondDestinationController.Object.TempDataProvider);
// Assert
Assert.True(mockSecondDestinationController.Object.TempData.ContainsKey("Key"));
Assert.True(mockSecondDestinationController.Object.TempData.ContainsKey("NewKey"));
}
[Fact]
public void TempDataRemovesKeyWhenRead()
{
// Arrange
Mock<Controller> mockController = new Mock<Controller>() { CallBase = true };
Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();
HttpSessionStateBase session = GetEmptySession();
mockContext.Setup(o => o.Session).Returns(session);
mockController.Object.ControllerContext = new ControllerContext(mockContext.Object, new RouteData(), mockController.Object);
// Act
mockController.Object.TempData.Add("Key", "Value");
mockController.Object.TempData.Save(mockController.Object.ControllerContext, mockController.Object.TempDataProvider);
// Assert
Assert.True(mockController.Object.TempData.ContainsKey("Key"));
Assert.True(mockController.Object.TempData.ContainsValue("Value"));
// Instantiate "destination" controller with the same session state and see that it gets the temp data
Mock<Controller> mockDestinationController = new Mock<Controller>() { CallBase = true };
Mock<HttpContextBase> mockDestinationContext = new Mock<HttpContextBase>();
mockDestinationContext.Setup(o => o.Session).Returns(session);
mockDestinationController.Object.ControllerContext = new ControllerContext(mockDestinationContext.Object, new RouteData(), mockDestinationController.Object);
mockDestinationController.Object.TempData.Load(mockDestinationController.Object.ControllerContext, mockDestinationController.Object.TempDataProvider);
// Assert
Assert.True(mockDestinationController.Object.TempData.ContainsKey("Key"));
// Act
object value = mockDestinationController.Object.TempData["Key"];
mockDestinationController.Object.TempData.Save(mockDestinationController.Object.ControllerContext, mockDestinationController.Object.TempDataProvider);
// Instantiate "second destination" controller with the same session state and see that it gets the temp data
Mock<Controller> mockSecondDestinationController = new Mock<Controller>() { CallBase = true };
Mock<HttpContextBase> mockSecondDestinationContext = new Mock<HttpContextBase>();
mockSecondDestinationContext.Setup(o => o.Session).Returns(session);
mockSecondDestinationController.Object.ControllerContext = new ControllerContext(mockSecondDestinationContext.Object, new RouteData(), mockSecondDestinationController.Object);
mockSecondDestinationController.Object.TempData.Load(mockSecondDestinationController.Object.ControllerContext, mockSecondDestinationController.Object.TempDataProvider);
// Assert
Assert.False(mockSecondDestinationController.Object.TempData.ContainsKey("Key"));
}
[Fact]
public void TempDataValidForSingleControllerWhenSessionStateDisabled()
{
// Arrange
Mock<Controller> mockController = new Mock<Controller>();
Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();
HttpSessionStateBase session = null;
mockContext.Setup(o => o.Session).Returns(session);
mockController.Object.ControllerContext = new ControllerContext(mockContext.Object, new RouteData(), mockController.Object);
mockController.Object.TempData = new TempDataDictionary();
// Act
mockController.Object.TempData["Key"] = "Value";
// Assert
Assert.True(mockController.Object.TempData.ContainsKey("Key"));
}
[Fact]
public void TryUpdateModelCallsModelBinderForModel()
{
// Arrange
MyModel myModel = new MyModelSubclassed();
IValueProvider valueProvider = new SimpleValueProvider();
Controller controller = new EmptyController();
controller.ControllerContext = GetControllerContext("someAction");
// Act
bool returned = controller.TryUpdateModel(myModel, "somePrefix", new[] { "prop1", "prop2" }, null, valueProvider);
// Assert
Assert.True(returned);
Assert.Equal(valueProvider, myModel.BindingContext.ValueProvider);
Assert.Equal("somePrefix", myModel.BindingContext.ModelName);
Assert.Equal(controller.ModelState, myModel.BindingContext.ModelState);
Assert.Equal(typeof(MyModel), myModel.BindingContext.ModelType);
Assert.True(myModel.BindingContext.PropertyFilter("prop1"));
Assert.True(myModel.BindingContext.PropertyFilter("prop2"));
Assert.False(myModel.BindingContext.PropertyFilter("prop3"));
}
[Fact]
public void TryUpdateModelReturnsFalseIfModelStateInvalid()
{
// Arrange
MyModel myModel = new MyModelSubclassed();
Controller controller = new EmptyController();
controller.ModelState.AddModelError("key", "some exception message");
// Act
bool returned = controller.TryUpdateModel(myModel, new SimpleValueProvider());
// Assert
Assert.False(returned);
}
[Fact]
public void TryUpdateModelSuppliesControllerValueProviderIfNoValueProviderSpecified()
{
// Arrange
MyModel myModel = new MyModelSubclassed();
IValueProvider valueProvider = new SimpleValueProvider();
Controller controller = new EmptyController();
controller.ValueProvider = valueProvider;
// Act
bool returned = controller.TryUpdateModel(myModel, "somePrefix", new[] { "prop1", "prop2" });
// Assert
Assert.True(returned);
Assert.Equal(valueProvider, myModel.BindingContext.ValueProvider);
}
[Fact]
public void TryUpdateModelSuppliesEmptyModelNameIfNoPrefixSpecified()
{
// Arrange
MyModel myModel = new MyModelSubclassed();
Controller controller = new EmptyController();
// Act
bool returned = controller.TryUpdateModel(myModel, new[] { "prop1", "prop2" }, new SimpleValueProvider());
// Assert
Assert.True(returned);
Assert.Equal(String.Empty, myModel.BindingContext.ModelName);
}
[Fact]
public void TryUpdateModelThrowsIfModelIsNull()
{
// Arrange
Controller controller = new EmptyController();
// Act & Assert
Assert.ThrowsArgumentNull(
delegate { controller.TryUpdateModel<object>(null, new SimpleValueProvider()); }, "model");
}
[Fact]
public void TryUpdateModelThrowsIfValueProviderIsNull()
{
// Arrange
Controller controller = new EmptyController();
// Act & Assert
Assert.ThrowsArgumentNull(
delegate { controller.TryUpdateModel(new object(), null, null, null, null); }, "valueProvider");
}
[Fact]
public void UpdateModelReturnsIfModelStateValid()
{
// Arrange
MyModel myModel = new MyModelSubclassed();
Controller controller = new EmptyController();
// Act
controller.UpdateModel(myModel, new SimpleValueProvider());
// Assert
// nothing to do - if we got here, the test passed
}
[Fact]
public void TryUpdateModelWithoutBindPropertiesImpliesAllPropertiesAreUpdateable()
{
// Arrange
MyModel myModel = new MyModelSubclassed();
Controller controller = new EmptyController();
// Act
bool returned = controller.TryUpdateModel(myModel, "somePrefix", new SimpleValueProvider());
// Assert
Assert.True(returned);
Assert.True(myModel.BindingContext.PropertyFilter("prop1"));
Assert.True(myModel.BindingContext.PropertyFilter("prop2"));
Assert.True(myModel.BindingContext.PropertyFilter("prop3"));
}
[Fact]
public void UpdateModelSuppliesControllerValueProviderIfNoValueProviderSpecified()
{
// Arrange
MyModel myModel = new MyModelSubclassed();
IValueProvider valueProvider = new SimpleValueProvider();
Controller controller = new EmptyController() { ValueProvider = valueProvider };
// Act
controller.UpdateModel(myModel, "somePrefix", new[] { "prop1", "prop2" });
// Assert
Assert.Equal(valueProvider, myModel.BindingContext.ValueProvider);
}
[Fact]
public void UpdateModelThrowsIfModelStateInvalid()
{
// Arrange
MyModel myModel = new MyModelSubclassed();
Controller controller = new EmptyController();
controller.ModelState.AddModelError("key", "some exception message");
// Act & assert
Assert.Throws<InvalidOperationException>(
delegate { controller.UpdateModel(myModel, new SimpleValueProvider()); },
"The model of type 'System.Web.Mvc.Test.ControllerTest+MyModel' could not be updated.");
}
[Fact]
public void UpdateModelWithoutBindPropertiesImpliesAllPropertiesAreUpdateable()
{
// Arrange
MyModel myModel = new MyModelSubclassed();
Controller controller = new EmptyController();
// Act
controller.UpdateModel(myModel, "somePrefix", new SimpleValueProvider());
// Assert
Assert.True(myModel.BindingContext.PropertyFilter("prop1"));
Assert.True(myModel.BindingContext.PropertyFilter("prop2"));
Assert.True(myModel.BindingContext.PropertyFilter("prop3"));
}
[Fact]
public void Json()
{
// Arrange
MyModel model = new MyModel();
Controller controller = new EmptyController();
// Act
JsonResult result = controller.Json(model);
// Assert
Assert.Same(model, result.Data);
Assert.Null(result.ContentType);
Assert.Null(result.ContentEncoding);
Assert.Equal(JsonRequestBehavior.DenyGet, result.JsonRequestBehavior);
}
[Fact]
public void JsonWithContentType()
{
// Arrange
MyModel model = new MyModel();
Controller controller = new EmptyController();
// Act
JsonResult result = controller.Json(model, "text/xml");
// Assert
Assert.Same(model, result.Data);
Assert.Equal("text/xml", result.ContentType);
Assert.Null(result.ContentEncoding);
Assert.Equal(JsonRequestBehavior.DenyGet, result.JsonRequestBehavior);
}
[Fact]
public void JsonWithContentTypeAndEncoding()
{
// Arrange
MyModel model = new MyModel();
Controller controller = new EmptyController();
// Act
JsonResult result = controller.Json(model, "text/xml", Encoding.UTF32);
// Assert
Assert.Same(model, result.Data);
Assert.Equal("text/xml", result.ContentType);
Assert.Equal(Encoding.UTF32, result.ContentEncoding);
Assert.Equal(JsonRequestBehavior.DenyGet, result.JsonRequestBehavior);
}
[Fact]
public void JsonWithBehavior()
{
// Arrange
MyModel model = new MyModel();
Controller controller = new EmptyController();
// Act
JsonResult result = controller.Json(model, JsonRequestBehavior.AllowGet);
// Assert
Assert.Same(model, result.Data);
Assert.Null(result.ContentType);
Assert.Null(result.ContentEncoding);
Assert.Equal(JsonRequestBehavior.AllowGet, result.JsonRequestBehavior);
}
[Fact]
public void JsonWithContentTypeAndBehavior()
{
// Arrange
MyModel model = new MyModel();
Controller controller = new EmptyController();
// Act
JsonResult result = controller.Json(model, "text/xml", JsonRequestBehavior.AllowGet);
// Assert
Assert.Same(model, result.Data);
Assert.Equal("text/xml", result.ContentType);
Assert.Null(result.ContentEncoding);
Assert.Equal(JsonRequestBehavior.AllowGet, result.JsonRequestBehavior);
}
[Fact]
public void JsonWithContentTypeAndEncodingAndBehavior()
{
// Arrange
MyModel model = new MyModel();
Controller controller = new EmptyController();
// Act
JsonResult result = controller.Json(model, "text/xml", Encoding.UTF32, JsonRequestBehavior.AllowGet);
// Assert
Assert.Same(model, result.Data);
Assert.Equal("text/xml", result.ContentType);
Assert.Equal(Encoding.UTF32, result.ContentEncoding);
Assert.Equal(JsonRequestBehavior.AllowGet, result.JsonRequestBehavior);
}
[Fact]
public void ExecuteDoesNotCallTempDataLoadOrSave()
{
// Arrange
TempDataDictionary tempData = new TempDataDictionary();
ViewContext viewContext = new ViewContext { TempData = tempData };
RouteData routeData = new RouteData();
routeData.DataTokens[ControllerContext.ParentActionViewContextToken] = viewContext;
routeData.Values["action"] = "SimpleAction";
RequestContext requestContext = new RequestContext(HttpContextHelpers.GetMockHttpContext().Object, routeData);
// Strict == no default implementations == calls to Load & Save are not allowed
Mock<ITempDataProvider> tempDataProvider = new Mock<ITempDataProvider>(MockBehavior.Strict);
SimpleController controller = new SimpleController();
controller.ValidateRequest = false;
// Act
((IController)controller).Execute(requestContext);
// Assert
tempDataProvider.Verify();
}
// Model validation
[Fact]
public void TryValidateModelGuardClauses()
{
// Arrange
Controller controller = new SimpleController();
// Act & Assert
Assert.ThrowsArgumentNull(
() => controller.TryValidateModel(null),
"model");
}
[Fact]
public void TryValidateModelWithValidModel()
{
// Arrange
Controller controller = new SimpleController();
TryValidateModelModel model = new TryValidateModelModel { IntegerProperty = 15 };
// Act
bool result = controller.TryValidateModel(model);
// Assert
Assert.True(result);
Assert.True(controller.ModelState.IsValid);
}
[Fact]
public void TryValidateModelWithInvalidModel()
{
// Arrange
Controller controller = new SimpleController();
TryValidateModelModel model = new TryValidateModelModel { IntegerProperty = 5 };
// Act
bool result = controller.TryValidateModel(model, "Prefix");
// Assert
Assert.False(result);
Assert.Equal("Out of range!", controller.ModelState["Prefix.IntegerProperty"].Errors[0].ErrorMessage);
}
[Fact]
public void ValidateModelGuardClauses()
{
// Arrange
Controller controller = new SimpleController();
// Act & Assert
Assert.ThrowsArgumentNull(
() => controller.ValidateModel(null),
"model");
}
[Fact]
public void ValidateModelWithValidModel()
{
// Arrange
Controller controller = new SimpleController();
TryValidateModelModel model = new TryValidateModelModel { IntegerProperty = 15 };
// Act
controller.ValidateModel(model);
// Assert
Assert.True(controller.ModelState.IsValid);
}
[Fact]
public void ValidateModelWithInvalidModel()
{
// Arrange
Controller controller = new SimpleController();
TryValidateModelModel model = new TryValidateModelModel { IntegerProperty = 5 };
// Act & Assert
Assert.Throws<InvalidOperationException>(
() => controller.ValidateModel(model, "Prefix"),
"The model of type '" + model.GetType().FullName + "' is not valid.");
Assert.Equal("Out of range!", controller.ModelState["Prefix.IntegerProperty"].Errors[0].ErrorMessage);
}
[Fact]
public void ValidateControllerUsesCachedResolver()
{
var controller = new EmptyController();
var resolver = controller.Resolver;
Assert.Equal(DependencyResolver.CurrentCache.GetType(), resolver.GetType());
}
[Fact]
public void CreateActionInvokerCallsIntoResolverInstance()
{
// Controller uses an IDependencyResolver to create an IActionInvoker.
var controller = new EmptyController();
Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();
Mock<IAsyncActionInvoker> actionInvokerMock = new Mock<IAsyncActionInvoker>();
resolverMock.Setup(r => r.GetService(typeof(IAsyncActionInvoker))).Returns(actionInvokerMock.Object);
controller.Resolver = resolverMock.Object;
var ai = controller.CreateActionInvoker();
resolverMock.Verify(r => r.GetService(typeof(IAsyncActionInvoker)), Times.Once());
Assert.Same(actionInvokerMock.Object, ai);
}
[Fact]
public void CreateActionInvokerCallsIntoResolverInstanceAndCreatesANewOneIfNecessary()
{
// If IDependencyResolver is set, but empty, falls back and still creates.
var controller = new EmptyController();
Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();
resolverMock.Setup(r => r.GetService(typeof(IAsyncActionInvoker))).Returns(null);
controller.Resolver = resolverMock.Object;
IActionInvoker ai = controller.CreateActionInvoker();
resolverMock.Verify(r => r.GetService(typeof(IAsyncActionInvoker)), Times.Once());
Assert.NotNull(ai);
}
[Fact]
public void CreateTempProviderWithResolver()
{
// Controller uses an IDependencyResolver to create an IActionInvoker.
var controller = new EmptyController();
Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();
Mock<ITempDataProvider> tempMock = new Mock<ITempDataProvider>();
resolverMock.Setup(r => r.GetService(typeof(ITempDataProvider))).Returns(tempMock.Object);
controller.Resolver = resolverMock.Object;
ITempDataProvider temp = controller.CreateTempDataProvider();
resolverMock.Verify(r => r.GetService(typeof(ITempDataProvider)), Times.Once());
Assert.Same(tempMock.Object, temp);
}
private class TryValidateModelModel
{
[Range(10, 20, ErrorMessage = "Out of range!")]
public int IntegerProperty { get; set; }
}
// Helpers
private class SimpleController : Controller
{
public SimpleController()
{
ControllerContext = new ControllerContext { Controller = this };
}
public void SimpleAction()
{
}
}
private static ControllerContext GetControllerContext(string actionName)
{
RouteData rd = new RouteData();
rd.Values["action"] = actionName;
Mock<HttpContextBase> mockHttpContext = HttpContextHelpers.GetMockHttpContext();
mockHttpContext.Setup(c => c.Session).Returns((HttpSessionStateBase)null);
return new ControllerContext(mockHttpContext.Object, rd, new Mock<Controller>().Object);
}
private static ControllerContext GetControllerContext(string actionName, string controllerName)
{
RouteData rd = new RouteData();
rd.Values["action"] = actionName;
rd.Values["controller"] = controllerName;
Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(c => c.Session).Returns((HttpSessionStateBase)null);
return new ControllerContext(mockHttpContext.Object, rd, new Mock<Controller>().Object);
}
private static Controller GetEmptyController()
{
ControllerContext context = GetControllerContext("Foo");
var controller = new EmptyController()
{
ControllerContext = context,
RouteCollection = new RouteCollection(),
TempData = new TempDataDictionary(),
TempDataProvider = new SessionStateTempDataProvider()
};
return controller;
}
private static HttpSessionStateBase GetEmptySession()
{
HttpSessionStateMock mockSession = new HttpSessionStateMock();
return mockSession;
}
private sealed class HttpSessionStateMock : HttpSessionStateBase
{
private Hashtable _sessionData = new Hashtable(StringComparer.OrdinalIgnoreCase);
public override void Remove(string name)
{
Assert.Equal<string>(SessionStateTempDataProvider.TempDataSessionStateKey, name);
_sessionData.Remove(name);
}
public override object this[string name]
{
get
{
Assert.Equal<string>(SessionStateTempDataProvider.TempDataSessionStateKey, name);
return _sessionData[name];
}
set
{
Assert.Equal<string>(SessionStateTempDataProvider.TempDataSessionStateKey, name);
_sessionData[name] = value;
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
private class EmptyController : Controller
{
public new void HandleUnknownAction(string actionName)
{
base.HandleUnknownAction(actionName);
}
public void PublicInitialize(RequestContext requestContext)
{
base.Initialize(requestContext);
}
// Test can expose protected method as public.
public new IActionInvoker CreateActionInvoker()
{
return base.CreateActionInvoker();
}
public new ITempDataProvider CreateTempDataProvider()
{
return base.CreateTempDataProvider();
}
}
private sealed class UnknownActionController : Controller
{
public bool WasCalled;
protected override void HandleUnknownAction(string actionName)
{
WasCalled = true;
}
}
private sealed class TempDataHomeController : Controller
{
public ActionResult Index()
{
// Save UserID into TempData and redirect to greeting page
TempData["UserID"] = "user123";
return RedirectToAction("GreetUser");
}
public ActionResult GreetUser()
{
// Check that the UserID is present. If it's not
// there, redirect to error page. If it is, show
// the greet user view.
if (!TempData.ContainsKey("UserID"))
{
return RedirectToAction("ErrorPage");
}
ViewData["NewUserID"] = TempData["UserID"];
return View("GreetUser");
}
}
public class BrokenController : Controller
{
public BrokenController()
{
ActionInvoker = new ControllerActionInvoker()
{
DescriptorCache = new ControllerDescriptorCache()
};
}
public ActionResult Crash()
{
TempData["Key1"] = "Value1";
throw new InvalidOperationException("Crashing....");
}
}
private sealed class TestRouteController : Controller
{
public ActionResult Index()
{
return RedirectToAction("SomeAction");
}
}
[ModelBinder(typeof(MyModelBinder))]
private class MyModel
{
public ControllerContext ControllerContext;
public ModelBindingContext BindingContext;
}
private class MyModelSubclassed : MyModel
{
}
private class MyModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
MyModel myModel = (MyModel)bindingContext.Model;
myModel.ControllerContext = controllerContext;
myModel.BindingContext = bindingContext;
return myModel;
}
}
}
internal class EmptyTempDataProvider : ITempDataProvider
{
public void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)
{
}
public IDictionary<string, object> LoadTempData(ControllerContext controllerContext)
{
return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
}
}
}
|