BaseTests.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Masuit.Tools.Test.Mvc.Mocks;
  2. using Moq;
  3. using System;
  4. using System.IO;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. using System.Web.Routing;
  8. namespace Masuit.Tools.Test.Mvc
  9. {
  10. public abstract class BaseTests
  11. {
  12. protected internal MockHttpResponse Response { get; set; }
  13. protected internal HttpContextBase Context { get; set; }
  14. protected internal MockHttpRequest Request { get; set; }
  15. protected internal MockHttpSession Session { get; private set; }
  16. protected string TestDirectoryPath()
  17. {
  18. return new DirectoryInfo(AppContext.BaseDirectory + ".\\Resources").FullName;
  19. }
  20. protected FileInfo TestFile(string fileName)
  21. {
  22. return new FileInfo($"{TestDirectoryPath()}\\{fileName}");
  23. }
  24. protected string FilePath(string fileName)
  25. {
  26. return TestFile(fileName).FullName;
  27. }
  28. protected BaseTests()
  29. {
  30. InitMocks();
  31. }
  32. protected void InitMocks()
  33. {
  34. var mockHttpContext = new Mock<HttpContextBase>();
  35. Context = mockHttpContext.Object;
  36. Session = new MockHttpSession();
  37. Request = new MockHttpRequest(new MockHttpFilesCollection(null));
  38. Response = new MockHttpResponse();
  39. mockHttpContext.Setup(ctx => ctx.Session).Returns(() => Session);
  40. mockHttpContext.Setup(ctx => ctx.Request).Returns(() => Request);
  41. mockHttpContext.Setup(ctx => ctx.Response).Returns(() => Response);
  42. mockHttpContext.Setup(ctx => ctx.Cache).Returns(() => HttpRuntime.Cache);
  43. }
  44. protected ControllerContext ControllerContext<T>(T controller) where T : ControllerBase
  45. {
  46. return new ControllerContext(Context, new RouteData(), controller);
  47. }
  48. protected ModelBindingContext BindingContext<T>()
  49. {
  50. return new ModelBindingContext
  51. {
  52. ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T))
  53. };
  54. }
  55. protected T MockObject<T>() where T : class
  56. {
  57. var mock = new Mock<T>();
  58. return mock.Object;
  59. }
  60. protected Mock<T> Mock<T>() where T : class
  61. {
  62. return new Mock<T>();
  63. }
  64. }
  65. }