Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unit Test JsonResult and Collections in MSTest

I am very new to unit testing even though i have been coding for a very long time. I want to make this a part of my way of development. I run into blocks on how to unit test things like a collection. I generally have my jQuery script calling ASP.Net Server side methods to get data and populate tables and the like. They look like

Get_*Noun*()  

which generally returns a JsonResult. Any ideas on what and how to test these using Unit tests using MSTest?

like image 933
mithun_daa Avatar asked Nov 29 '11 22:11

mithun_daa


People also ask

How do I assert JsonResult?

We can return jsonResult via invoking the Josn() method in the controller, in general, I will pass one anonymous object such as Josn(new {isSuccess = true, message="It's success!"}); var actionResult = controller. JosnMethod() as JsonResult; Assert.

How do I run a MSTest unit test?

To run MSTest unit tests, specify the full path to the MSTest executable (mstest.exe) in the Unit Testing Options dialog. To call this dialog directly from the editor, right-click somewhere in the editor and then click Options.

Is MSTest a testing framework?

MSTest is a number-one open-source test framework that is shipped along with the Visual Studio IDE. It is also referred to as the Unit Testing Framework. However, MSTest is the same within the developer community. MSTest is used to run tests.

What is the use of JsonResult in MVC?

What is JsonResult ? JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format).


1 Answers

You should be able to test this just like anything else, provided you can extract the values from the JsonResult. Here's a helper that will do that for you:

private T GetValueFromJsonResult<T>(JsonResult jsonResult, string propertyName) {     var property =         jsonResult.Data.GetType().GetProperties()         .Where(p => string.Compare(p.Name, propertyName) == 0)         .FirstOrDefault();      if (null == property)         throw new ArgumentException("propertyName not found", "propertyName");     return (T)property.GetValue(jsonResult.Data, null); } 

Then call your controller as usual, and test the result using that helper.

var jsonResult = yourController.YourAction(params); bool testValue = GetValueFromJsonResult<bool>(jsonResult, "PropertyName"); Assert.IsFalse(testValue); 
like image 58
David Ruttka Avatar answered Sep 21 '22 09:09

David Ruttka