Showing posts with label Moq. Show all posts
Showing posts with label Moq. Show all posts

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, August 29, 2016

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!


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!!



Monday, August 22, 2016

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!

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, March 25, 2016

Mocking a private property setter in your Unit Tests using Moq

I recently encountered a requirement whereby I had to set the value for a property that had a private setter in my Mock objects.

Fortunately, Moq has a solution for this!

You can use the .SetupGet method to set a private property as follows:


myMock.SetupGet(m => m.MyPrivateSetter).Returns(myValue);

If you want to read more about how to accomplish things using Moq, you can read the QuickStart and API Docs here:

https://github.com/Moq/moq4/wiki/Quickstart

http://www.nudoq.org/#!/Packages/Moq/Moq/Mock(T)/M/SetupGet(TProperty)

Sunday, January 4, 2015

Getting started Unit Testing with Moq

If you are just starting to learn about Unit Testing using Mocking Frameworks such as Moq, unfortunately, the documentation out there for Moq is pretty sparse.  It consists of some basic code samples with very little explanation of what they mean or how to properly use them in different situations.

You can check out the Moq Quickstart over here: https://github.com/Moq/moq4/wiki/Quickstart

Fortunately, there is a fairly good blog post on how to use Moq here:

http://www.deanhume.com/Home/BlogPost/basic-introduction-to-writing-unit-tests-with-moq/16

http://deanhume.com/home/blogpost/basic-introduction-to-writing-unit-tests-with-moq---part-2/23

Of course, you can also check out PluralSight's courses on Moq as well (requires a subscription): http://www.pluralsight.com/courses/mocking-with-moq

Thursday, January 1, 2015

Unit Testing ASP.NET Web API

If you are looking for guidance on how to Unit Test ASP.NET Web API Controllers, you can find some excellent guidance here:
http://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-with-aspnet-web-api

This example also includes using Moq as your Mocking framework to mock out functionality in your Web API Controllers:
http://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api

This is also another good article on Unit Testing Web API Controllers: http://blogs.msmvps.com/theproblemsolver/2013/11/13/unit-testing-a-asp-net-webapi-2-controller/