Showing posts with label Unit Testing. Show all posts
Showing posts with label Unit Testing. Show all posts

Saturday, October 1, 2016

Running Code Coverage for Unit Tests in Visual Studio 2015

If you want to run Code Coverage for your Unit Tests, unfortunately, you will need to use Visual Studio 2015 Enterprise Edition.  Visual Studio 2015 Professional Edition still does not offer this crucial feature for most .NET Developers.

In any case, once you run the Unit Tests for your application from within Test Explorer, you can click on the "Run.." link to pull down the drop down menu options:


From there, you can select the option for "Analyze Code Coverage for All Tests", which will then present you with a "Code Coverage Results" pane:


Within the "Code Coverage Results" pane, you can further drill down into your individual namespaces and classes to determine how well your Unit Tests are covering your code!


Friday, September 23, 2016

Mocking TempData in ASP.NET MVC Unit Tests

If you want to mock TempData in your ASP.NET MVC Unit Tests, you will encounter some difficulties with accomplishing this since TempData is based on the Controller context and therefore cannot be readily mocked.

If you start doing some digging for solutions on how to accomplish this, you will inevitable come across this article: http://weblogs.asp.net/leftslipper/mvc-unit-testing-controller-actions-that-use-tempdata

Of course, this works just fine if you only want to deal with TempData, but what if you find yourself needing to mock other objects that are dependent on the Controller context as well such as Session State?

Well, this is where MvcContrib TestHelper comes to the rescue!  https://cgeers.wordpress.com/2011/08/07/asp-net-mvc-mocking-session-state/

Using just a few lines of code, this NuGet package will help you set up all of your MVC Controller dependencies such as TempData as well as Session State and several others!

Unfortunately, when you attempt to install this NuGet package into your Unit Testing project, you will end up seeing some unwanted dependencies (including an older version of ASP.NET MVC):



Fortunately, another clever developer has updated this library to support ASP.NET MVC 4 and later versions!

The name of this NuGet package is StudioDonder.MvcContrib.Mvc4.TestHelper.  You can download this NuGet package from here: https://www.nuget.org/packages/StudioDonder.MvcContrib.Mvc4.TestHelper/

Even though it was originally built for ASP.NET MVC 4, it works just fine with ASP.NET MVC 5 as well:



After installing this NuGet package, you can use it just as if it was the original MvcContrib.TestHelper NuGet package in your code as follows:


Monday, September 5, 2016

Unit Testing Custom ASP.NET MVC Validation Attributes

When you are using custom ASP.NET MVC Validation Attributes, you may encounter a problem when attempting to Unit Test this functionality since inheriting from the ValidationAttribute class may require a method such as the following:


This works just fine when testing the public implementation of IsValid, but what if you are implementing the protected method of IsValid? Well, as you will quickly discover, you will not be able to easily Unit Test protected methods:


So how do you work around this limitation?

Well, thanks to this handy article (http://www.codeproject.com/Articles/9715/How-to-Test-Private-and-Protected-methods-in-NET), you can do something like the following:



Now, when you write your Unit Test, you will do something like this to ACTUALLY Unit Test your Custom Validation Attribute:

Wednesday, August 31, 2016

Unit Testing jQuery with QUnit

One of the main problems with writing JavaScript or jQuery code is that it is difficult to debug and test.

Well, that is where QUnit comes in!

QUnit allows Unit Testing your JavaScript/jQuery code through a standard web browser.

You can learn about QUnit here: https://qunitjs.com/

If you are working with older documentation for QUnit, you may encounter error messages regarding deprecated methods, in which case you should consult the upgrade guide: https://qunitjs.com/upgrade-guide-2.x/

To get started with a basic sample of a QUnit Unit Test, you can use the following sample code:


Monday, August 29, 2016

Unit Testing Data Annotation Validation/View Model Validation

If you are building functionality for validating your ViewModels either using IValidateableObject or through using Data Annotations/ValidationAttribute, you will probably want to be able to Unit Test this functionality as well!

Well, thankfully, this can be done quite easily by following this article: https://visualstudiomagazine.com/articles/2015/06/19/tdd-asp-net-mvc-part-4-unit-testing.aspx


Unit Testing ASP.NET MVC with Request.IsAjaxRequest()

One of the difficulties in Unit Testing ASP.NET MVC Web Applications is any dependence on HttpContext.

Code that you may encounter frequently in your ASP.NET MVC Controller methods is a check for whether or not the Request object is an AJAX Request.

So how exactly do you Unit Test this for your ASP.NET MVC Web Applications?

Well, there is an article on how to do just that!  http://thegrayzone.co.uk/blog/2010/03/mocking-request-isajaxrequest/

Once you set the Request Headers for the Mocked HttpRequestBase object, you will be able to return true for the Ajax request and complete your Unit Tests!


Sunday, August 28, 2016

Add xUnit.Net support to TeamCity

If you want to run your xUnit.Net Unit Tests to your TeamCity Builds, you can accomplish this quite conveniently using the xUnit.Net TeamCity plugin.

You can download the latest release of the xUnit.Net TeamCity plugin from here: https://github.com/carlpett/xUnit-TeamCity/releases/tag/1.1.3

Once you have installed the TeamCity plugin, you will be able to use xUnit.Net as a TeamCity Build step as follows:


That is all there is to it!!

Friday, August 26, 2016

Mocking Entity Framework Database Transactions

If you are writing Unit Tests for any of your classes that leverage Entity Framework, you should be able to Mock most operations leveraged by Entity Framework.

However, Entity Framework 6 introduces features for wrapping your operation in a BeginTransaction() statement as described here: https://msdn.microsoft.com/en-us/data/dn456843.aspx

The problem with this scenario, of course, is that this code cannot easily be Mocked!

Well, what do you do in these scenarios?

Well, first of all, I would recommend looking at the use case scenarios to determine if you really need this functionality since Microsoft describes this in the article:


In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete on the database the framework will wrap that operation in a transaction. This transaction lasts only long enough to execute the operation and then completes. When you execute another such operation a new transaction is started.

Therefore, transactions are being used as required by Entity Framework for insert, update and delete operations!!

If you read articles such as this which does some additional examination on the repercussions of using Entity Framework Database Transactions (https://coderwall.com/p/jnniww/why-you-shouldn-t-use-entity-framework-with-transactions), you will see that the recommendation is to NOT USE Entity Framework Database Transactions (especially with Web Applications).

Therefore, unless the business logic ABSOLUTELY requires the use of Entity Framework Database Transactions in this manner, you can probably safely remove this code and thereby save yourself a great deal of hassle while writing your Unit Tests!!



Wednesday, August 24, 2016

Unit Testing ASP.NET MVC

If you have ever had to write a Unit Test for your ASP.NET MVC Web Application, you may quickly discover that writing Unit Tests for ASP.NET MVC for all but the most basic scenarios is quite difficult!

This is because Unit Tests, by default, do not understand how to test the various conventions used in ASP.NET MVC for routing to Views etc.

So how exactly do you solve this dilemma?

Well, thankfully, there is a NuGet package that allows you to fill in the gaps left by the Unit Testing framework!  The name of this NuGet package is TestStack.FluentMVCTesting: http://fluentmvctesting.teststack.net/

Here is a list of some of the basic types of statements you can include in your MVC Unit Tests using TestStack.FluentMVCTesting: http://fluentmvctesting.teststack.net/docs/examples

Tuesday, August 23, 2016

Unit Testing Kendo UI

If you want to Unit Test Kendo UI, unfortunately, there is no documentation on how to accomplish this on the Telerik website.

But, thanks to Stack Overflow, you can find a handy example on Unit Testing functionality for Kendo UI: http://stackoverflow.com/questions/14667911/unit-testing-asp-net-mvc4-controller-with-kendo

However, I prefer to use MSTest as my Unit Testing framework and having a few things outlined in the Unit Test to make the Unit Test a bit clearer as follows:

Monday, August 22, 2016

Using AutoFixture in your Unit Tests

If you are writing Unit Tests, you may frequently run into a need to autogenerate test or dummy data for your Unit Tests.

For many cases, you can use a framework such as NBuilder, however, NBuilder has numerous limitations in that it is primarily geared towards generating test data for classes which have default class constructors, but it is not as useful for generating test data for primitive types such as strings and integers.

So what do you do in those cases?  Well, that is where AutoFixture (https://github.com/AutoFixture/AutoFixture) comes in!

AutoFixture is available as a NuGet package and fills in many of the gaps that are left by a framework such as NBuilder.  It allows the generation of random strings and integers as well as allowing the generation of test objects in a manner similar to NBuilder: https://github.com/AutoFixture/AutoFixture/wiki/Cheat-Sheet







Mocking HttpClient in your ASP.NET Web API Unit Tests

If you use HttpClient in your Unit Tests, you may encounter a great deal of difficulty with using this object since this object is not easily mocked using a Mocking Framework such as Moq.  In fact, you may encounter an error message such as the following:


There are a great number of solutions posted on the Internet on how to resolve this issue by creating a custom HttpMessageHandler and then passing this in the constructor of the HttpClient to create the HttpClient object for Unit Testing.

However, a clever developer has already provided a very handy NuGet package to allow you to do just that!  https://github.com/richardszalay/mockhttp

MockHttp is just one particular NuGet package that supports Unit Testing of the HttpClient.  There are other such as HttpClient.Helpers https://github.com/PureKrome/HttpClient.Helpers

However, the use of MockHttp is very intuitive and I highly prefer using it in my Unit Tests.

One of the things that I like to do, however, is use frameworks such as NBuilder or AutoFixture to help me generate test data rather than manually type this information into my Unit Tests myself.  But, one of the problems with using an object such as HttpResponseMessage is that it does not lend itself well to generating all of the properties needed to pass a Unit Test such as setting the Content of the HttpResponseMessage.

Therefore, I had to use a solution such as the following to get my entire Unit Test to work:


Monday, August 8, 2016

Mocking Entity Framework for your Unit Tests using NBuilder

If you need to Mock Entity Framework in your Unit Tests you may end up referring to this article: https://msdn.microsoft.com/en-us/library/dn314429.aspx

In the article, they require you to create a test collection of your DbSet objects which are subsequently passed to your DbContext instance.

In addition, if you have multiple DbSet objects which are involved in a particular query, then this increases your workload even further!

However, you can use a framework such as NBuilder which is available as a NuGet package in order to simplify some of this code for you:


Alternatively, you can use some NuGet packages which takes away some of the extra setup for Mocking Entity Framework such as the following:

https://github.com/RichardSilveira/EntityFramework.MoqHelper

https://github.com/scott-xu/EntityFramework.Testing

Could not find a parameterless constructor when using Moq

If you need to Mock objects which expect parameters in the constructor, you may encounter a message such as the following:

"Can not instantiate proxy of class: DataAccess.DataModel.MyDbContext. Could not find a parameterless constructor."

Based on the error message, the solution requires you to pass a constructor to the parameter of your Mocked object.

So how exactly do you do that?

Well, the solution is, in fact, rather easy!

You just pass the required parameter to your Mocked object like so:


In this case, I am passing the database connectionString as a parameter to my Mocked DbContext object so that it can instantiate the object appropriately. That is all there is to it!

Friday, August 5, 2016

Unit Testing ASP.NET Web API using Attribute-based Routing

If you review any Unit Test code samples for ASP.NET Web API, you will find examples on how to Unit Tests when using CreatedAtRoute but they only refer to using the Default Routing rules available in WebApiConfig.cs.

So what do you do if you are using Attribute-based routing?

Well, while this scenario is poorly documented, there is a solution for this as well!

You start by using the Route Name attribute on  your Post method as follows:


Now, if you want to Unit Test that code, you can do something like the following:

That is all that is needed in order to support Unit Testing with Attribute-based routing!

Thursday, August 4, 2016

Unit Testing with AutoMapper

If you are using AutoMapper in your projects, you may know that there are multiple ways to use AutoMapper within your application.  There is both static and instance based configuration for AutoMapper.  https://github.com/AutoMapper/AutoMapper/wiki/Static-and-Instance-API

The most common method of using AutoMapper in most applications is using the Static API.  However, if you are used to using an IoC container such as Ninject, you may consider this problematic when it comes to your Unit Tests, because when you begin executing Unit Tests which depend on the static instance of AutoMapper, you may receive an error such as this:


So how do you work around this exception?

Well, if you are using a Unit Testing framework such as MSTest, the solution is very simple!

You can leverage the [TestInitialize] attribute to initialize your AutoMapper configuration before your Unit Tests execute like so:



Now, when you run your Unit Tests which leverage the static instance of AutoMapper, they should execute without any exceptions or errors!!

Unit Testing with MSTest

Even though many development teams are beginning to transition over to xUnit.Net for their Unit Tests, many teams are still continuing to develop Unit Tests with MSTest simply because the Visual Studio IDE integration is much better than xUnit.Net and it comes with the Visual Studio IDE out-of-the-box without installing any additional packages or extensions.

Therefore, if you are also working with MSTest, then you will probably want to use a handy reference guide for working with MSTest!

Microsoft has created a basic reference guide for MSTest:  https://msdn.microsoft.com/en-us/library/ms243147(v=vs.90).aspx

Of course, this guide has not been updated in several years which probably explains why many developers are beginning to move over to xUnit.Net which is better maintained and more frequently updated.

In any case, hopefully this guide helps you in writing your MSTest Unit Tests!

Wednesday, August 3, 2016

Returning null values from a Unit Test with Moq

In some cases when you are writing Unit Tests with Moq, you may have to return a null value from your Mocked object.

Unfortunately, if you directly attempt to return null from a Mocked object though, you will receive an error message.

Therefore, how do you return null from a Mocked object?

Well, the answer is deceptively simple!  You simply assign a null value to the expected object and simply return that null object as follows:


Friday, July 29, 2016

Running Visual Studio Unit Tests in TeamCity

As I start writing Unit Tests for my application, I usually also want to ensure that all of my Unit Tests are also passing whenever I check in my code!

The easiest way to accomplish this is to integrate the execution of my Unit Tests within TeamCity is to add a "Visual Studio Tests" build step:



Once you add the Visual Studio Tests Build Step, you will need to add the paths to the Unit Test assemblies.  I usually like to create TeamCity parameters and then pass the list of Unit Test assemblies to the Visual Studio Tests Build Step.



However, even though it is stated in the TeamCity User Interface and documentation that you can pass multiple Unit Test assemblies by including each path on a separate line, this has been quite unreliable since in a long list of Unit Test assemblies, any problems are not reported if those Unit Test assemblies are missing!  Therefore, I prefer to create separate Build Steps for each of my Unit Test assemblies to ensure I am able to see any errors that occur with any of my Unit Tests:





That is all there is to it!!

Tuesday, April 19, 2016

Mocking HttpContext in Unit Tests

One of the banes of writing Unit Tests is dealing with HttpContext which does not have an interface which can be easily Mocked like most other custom classes.

Fortunately, though, Microsoft has created a base class called HttpContextBase!

In my particular case, I needed to figure out how to mock HttpContext to use it in Unit Testing HttpCookie creation and retrieval.  I followed this article for guidance on just how to accomplish this task: http://blog.paulhadfield.net/2010/09/mocking-httpcookiecollection-in.html


Mock<HttpContextBase> HttpContextMock = new Mock<HttpContextBase>();
Mock<HttpRequestBase> RequestMock = new Mock<HttpRequestBase>();
Mock<HttpResponseBase> ResponseMock = new Mock<HttpResponseBase>();

HttpContextMock.Setup(x => x.Request).Returns(RequestMock.Object);
HttpContextMock.Setup(x => x.Response).Returns(ResponseMock.Object);
ResponseMock.Setup(r => r.Cookies).Returns(new HttpCookieCollection());

Using this Mock Setup code, I could now Unit Test my code which was dependent on HttpContext as well as the Request and Response objects for my HttpCookies!!