How to unit test a method that does automatic deserialization using MVC - asp.net-mvc

I have a method that is declared as so:
public ActionResult Request(Request request)
{
The method is called using JavaScript, but a string is passed in. The deserialization happens automatically.
Now I want to unit test this mimicking what the JavaScript would be passing in, which is a string. How do I unit test using a string instead of Request? When I create my unit test, it expects me to pass in the deserialized type which isn't the end of the world, but it would be nice if I could just copy the string request that gets sent in from the client and test with that.
Is this even possible... to force the automatic deserialization that normally happens?
TrackController c = new TrackController();
c.Request(jsonString);

Deserializing the json into your concrete model object is really the responsibility of the MVC model binder, so I don't think that should be included in the unit test of the controller action.
However I do see some value in testing that you are creating your requests correctly, but I think this is a better fit for an integration test.
You could potentially make http requests to your website directly, which would validate if you're passing correct json to your action.
See more here:
POSTing JSON to URL via WebClient in C#

Related

How to UnitTest System.Web.Mvc.Html.InputExtensions.TextBoxFor?

Edit : I am not trying to UnitTest TextBoxFor, but the code that uses it, However mocking objects and passing it to the code causes null reference exception without any hints on what property did not have a value, som properties like Request can not even be mocked.
How to UnitTest System.Web.Mvc.Html.InputExtensions.TextBoxFor ?
From googling around it seems that TextBoxFor is not UnitTestable, one can not mock the required parameters and get a result back, what is a unit testable alternative ?
The overuse static functions in MVC goes everything OO. The base units of in MVC are not even unit testable, or is there a another way to test?
Here is a link to one of the articles I used try to mockup objects so that I can test the custome Html Helper
http://community.embarcadero.com/blogs/entry/unit-testing-html-helpers-for-aspnet-mvc-38638

Is it really necessary to test controller methods?

When I design MVC apps, I typcially try to keep almost all logic (as much as possible) out of my app. I try to abstact this into a service layer which interfaces with my repositories and domain entities.
So, my controller methods end up looking something like this:
public ActionResult Index(int id)
{
return View(Mapper.Map<User, UserModel>(_userService.GetUser(id)));
}
So assuming that I have good coverage testing my services, and my action methods are simple like the above example, is it overkill to unit test these controller methods?
If you do build unit tests for methods that look like this, what value are you getting from your tests?
If you do build unit tests for methods that look like this, what value
are you getting from your tests?
You can have unit tests that assert:
That the GetUser method of the _userService was invoked, passing the same int that was passed to the controller.
That the result returned was a ViewResult, instead of a PartialViewResult or something else.
That the result's model is a UserModel instance, not a User instance (which is what gets returned from the service).
Unit tests are as much a help in refactoring as asserting the correctness of the application. Helps you ensure that the results remain the same even after you change the code.
For example, say you had a change come in that the action should return a PartialView or JsonResult when the request is async/ajax. It wouldn't be much code to change in the controller, but your unit tests would probably fail as soon as you changed the code, because it's likely that you didn't mock the controller's context to indicate whether or not the request is ajax. So this then tells you to expand on your unit tests to maintain the assertions of correctness.
Definitely value added IMO for 3 very simple methods which shouldn't take you longer than a couple of minutes each to write.

ASMX web service, external WSDLs *without* wsdl.exe

I'm working on some legacy code, and I need an asmx to implement a particular wsdl, which is being provided to me.
I would like to receive the root element of the message as either an XmlDocument or XmlNode, rather than the wsdl.exe generated object graph. Is this even possible?
First of all, you should use svcutil.exe, not wsdl.exe, unless you have no other choices.
Second, you don't need either program to implement an external WSDL. Just go write your service so that the XML Serializer will properly serialize and deserialize the incoming message. In particular, if you like processing XML, try this:
[WebMethod]
public XmlElement SomeOperation(XmlElement parameter)
{
}
I believe that the same works with the newer XElement class.
In WCF (which is what you should be using, since Microsoft now considers ASMX web services to be "legacy technology"), I believe you should use the Message type:
[OperationContract]
Message SomeOperation(Message parameter);

How to write test case for mvc action filters?

I have an action filter which i got from the below link
http://blog.wekeroad.com/blog/aspnet-mvc-securing-your-controller-actions/
there is something called "RequiresAuthenticationAttribute"
for this i need to write test case.
how can i do this? form some of the blogs i read that we need to mock httcontext.
How can i mock this? what is the procedure that i need to do? is there any link for this?
Don't use the [RequiresAuthentication] attribute from Rob's blog. It's meant for a very old pre-release version of MVC. Use the in-box [Authorize] attribute instead.
Since the [Authorize] attribute is written by the MVC team, you don't need to unit test its logic. However, if you want, you can verify that it's applied to your controllers or actions. Simply get the Type or MethodInfo you're interested in, then call its GetCustomAttributes() method to get instances of AuthorizeAttribute. You can inspect those instances for the values that you expect.
If you want, you can look at the source code of AuthorizeAttribute for information on writing your own filter. Additionally, you can look at the official unit test of this type, so if you do end up writing a filter you can use a similar method to write your own type's unit tests.

How do I unit test an ActionFilter in ASP.NET MVC?

There is an ActionFilter on my controller-class. The OnActionExecuting method gets called, when an action of the controller is called in a web application.
Now I call the Action in a UnitTest:
NiceController niceController = new NiceController();
ActionResult result = niceController.WhateverAction();
Is there a way to have the ActionFilter called?
In order to have the ActionFilter called automatically, you are going to need to run the controller action invoker. This is possible, but it means that the MVC framework will try and execute the result. This means that you would have to use mocks to stub out the execution of the result. Again, that is possible, but it means that your unit test is becoming more mocks than actual code. It may be more correct to just test the filter directly. After all, the fact that OnActionExecuting is called is a feature of the framework, and you don't need to unit test the framework itself.
But I think that what you're really saying is that you want to test WhateverAction, and that action cannot work unless the ActionFilter has executed.
First, I would ask questions about this design. Is this correct? It might be. It is reasonable, for example, that an action with the Authorize attribute could presume that when it executes there is a logged in user. Of course, the action should test this, but the presumption is safe. On the other hand, actions should probably not require filters to do action-specific initialization. So you should ask the question, but the answer they well be that the design is correct.
In this case, the best decision for a unit test might be to manually execute the filter in the unit test, and to write a separate unit test which proves that the action is decorated with the correct attribute.
to write a separate unit test which proves that the action is decorated with the correct attribute
Here is how you can write such a unit test
Type t = typeof(MyController);
Assert.IsTrue(t.GetCustomAttributes(typeof(MyCustomAttribute)).Length > 0);

Resources