Created
May 2, 2014 16:24
-
-
Save andrewwho/387c9993ce88e7bb3cb4 to your computer and use it in GitHub Desktop.
MVC Unit Test with Mock
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class HomeController : Controller | |
| { | |
| public ActionResult Index() | |
| { | |
| return Json(true, JsonRequestBehavior.AllowGet); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [TestClass] | |
| public class APITest | |
| { | |
| private static string invalidSessionKey = "NotAValidKey"; | |
| [TestMethod] | |
| public void AccessAPIWithValidSessionKey() | |
| { | |
| ApiHomeController c = new ApiHomeController(); | |
| var mocks = new ContextMocks(c); | |
| var request = mocks.Request; | |
| var response = mocks.Response; | |
| request.SetupGet(x => x.Headers).Returns( | |
| new System.Net.WebHeaderCollection { | |
| {"SessionKey", invalidSessionKey} | |
| } | |
| ); | |
| //System.Diagnostics.Debugger.Break(); | |
| Assert.IsTrue(response.Object.StatusCode == 401); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ContextMocks | |
| { | |
| public Mock<HttpContextBase> HttpContext { get; set; } | |
| public Mock<HttpRequestBase> Request { get; set; } | |
| public Mock<HttpResponseBase> Response { get; set; } | |
| public RouteData RouteData { get; set; } | |
| public ContextMocks(Controller controller) | |
| { | |
| //define context objects | |
| HttpContext = new Mock<HttpContextBase>(); | |
| Request = new Mock<HttpRequestBase>(); | |
| Response = new Mock<HttpResponseBase>(); | |
| HttpContext.Setup(x => x.Request).Returns(Request.Object); | |
| HttpContext.Setup(x => x.Response).Returns(Response.Object); | |
| //you would setup Response, Session, etc similarly with either mocks or fakes | |
| //apply context to controller | |
| RequestContext rc = new RequestContext(HttpContext.Object, new RouteData()); | |
| controller.ControllerContext = new ControllerContext(rc, controller); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment