Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I test an HTTP-Post with Moq in ASP.NET?

i've got the following Action Method I'm trying to moq test. Notice the AcceptVerbs? I need to make sure i'm testing that.

here's the method.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Include = "Subject, Content")]Post post,
    HttpPostedFileBase imageFileName)
{
  ...
}

here's the moq code i have...

[TestMethod]
public void Create_Action_snip_sniop_When_Http_Post_Is_Succesful()
{
    // Arrange.
    var mock = new Mock<ControllerContext>();
    mock.SetupGet(m => m.HttpContext.Request.HttpMethod).Returns("POST");

    // Snip some other arrangements.

    var controller = PostController;
    controller.ControllerContext = mock.Object;

    // Act.
    var viewResult = controller.Create(post, image.Object) as ViewResult;

    // Assert.
    Assert.IsNotNull(viewResult);

    // TODO: Test that the request was an Http-Post.

what do i need to do to verify the request was a post?

like image 936
Pure.Krome Avatar asked Apr 05 '09 13:04

Pure.Krome


People also ask

Can we mock static methods using Moq?

You can use Moq to mock non-static methods but it cannot be used to mock static methods. Although static methods cannot be mocked easily, there are a few ways to mock static methods. You can take advantage of the Moles or Fakes framework from Microsoft to mock static method calls.

Can I mock HttpClient?

Mocking HttpClient is possible although an arduous task. Luckily there is still a great way to unit test the code. The solution is to mock HttpMessageHandler and pass this object to the HttpClient constructor. When we use the message handler to make HTTP requests, we achieve our unit testing goals.

What is Moq testing C#?

Moq is a mocking framework for C#/. NET. It is used in unit testing to isolate your class under test from its dependencies and ensure that the proper methods on the dependent objects are being called.


1 Answers

Your attribute won't be invoked when running as a unit test because it is normally invoked by the ControllerActionInvoker as part of the Mvc "stack". What I've done in cases like this is to write a test to make sure that the correct attribute is applied to the action with the correct parameters. Then I trust that the framework will do its job correctly.

Doing this requires reflection:

 public void Only_posts_are_allowed_to_my_action()
 {
       var method = typeof(MyController).GetMethod("MyAction");
       var attribute = method.GetCustomAttributes(typeof(AcceptVerbsAttribute),false)
                             .Cast<AcceptVerbsAttribute>()
                             .SingleOrDefault();

       Assert.IsNotNull( attribute );
       Assert.AreEqual( 1, attributes.Count() );
       Assert.IsTrue( attributes.Contains( HttpVerbs.Post ) );
 }
like image 130
tvanfosson Avatar answered Oct 01 '22 00:10

tvanfosson