ivaylokenov

MyTested.Mvc Route & Model Binding Testing

Feb 15th, 2016
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. // Some random type
  2. public class RandomModel
  3. {
  4.     public int Integer { get; set; }
  5.  
  6.     public string String { get; set; }
  7. }
  8.  
  9. // Action request model with various binding sources
  10. public class BindingModel
  11. {
  12.     [FromBody]
  13.     public RandomModel Body { get; set; }
  14.  
  15.     [FromForm(Name = "MyField")]
  16.     public string Form { get; set; }
  17.  
  18.     [FromQuery(Name = "MyQuery")]
  19.     public string Query { get; set; }
  20.  
  21.     [FromRoute(Name = "id")]
  22.     public int Route { get; set; }
  23.  
  24.     [FromHeader(Name = "MyHeader")]
  25.     public string Header { get; set; }
  26. }
  27.  
  28. // Controller with POST action binding our model and a dependency injected service
  29. public class MyController : Controller
  30. {
  31.     [HttpPost]
  32.     public IActionResult Action(BindingModel model, [FromServices]IUrlHelperFactory urlHelper)
  33.     {
  34.         return View();
  35.     }
  36. }
  37.  
  38. // Test - PASSES!!!
  39. [Fact]
  40. public void UltimateSuperDuperCrazyModelBindingTest()
  41. {
  42.     MyMvc
  43.         .Routes()
  44.         .ShouldMap(request => request
  45.             .WithLocation("/My/Action/100?myQuery=Test")
  46.             .WithMethod(HttpMethod.Post)
  47.             .WithJsonBody(new { Integer = 1, String = "MyBodyValue" })
  48.             .WithFormField("MyField", "MyFieldValue")
  49.             .WithHeader("MyHeader", "MyHeaderValue"))
  50.         .To<MyController>(c => c.Action(
  51.             new BindingModel
  52.             {
  53.                 Body = new RandomModel { Integer = 1, String = "MyBodyValue" },
  54.                 Form = "MyFieldValue",
  55.                 Route = 100,
  56.                 Query = "Test",
  57.                 Header = "MyHeaderValue"
  58.             },
  59.             From.Services<IUrlHelperFactory>()));
  60. }
  61.  
  62. // P.S. Do not write such actions! :)
Advertisement
Add Comment
Please, Sign In to add comment