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?
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.
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.
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 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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With