How to fix the Initialization method TestInitialize threw exception problem in In Visual Studio 2010 Unit Testing How to fix the Initialization method TestInitialize threw exception problem in In Visual Studio 2010 Unit Testing

How to fix the Initialization method TestInitialize threw exception problem in In Visual Studio 2010 Unit Testing

The Problem

You are making an ASP.net MVC 3 web application, and being a good person, you are unit testing as much as possible.  You have properly separated your database from your business objects and every other good practice.  However, when you unit test your controllers, you throw in a fake DBContext (I am assuming you are using the Entity Framework and Moq) and all of a sudden, you get the following error

<b>Failed 1 tests.</b>
Initialization method [YourTestClass].TestInitialize threw exception. System.ArgumentNullException: System.ArgumentNullException: Value cannot be null.
Parameter name: source.

Which certainly makes for one of the least helpful error messages of all time.

The Cause

The problem seems to be lazy loading and the DBSet Feature of Entity Framework.  For example the below passage in your source code below will throw the error

public virtual DbSet<Setting> Settings { get; set; }
public virtual DbSet<AccountSource> AccountSources { get; set; }

This bit of code will not thow the error

public DbSet<Setting> Settings { get; set; }
public DbSet<AccountSource> AccountSources { get; set; }

The problem seems to be entirely in the initialization method.

The Solution

Rather irritating isn’t it?  Especially since Lazy Loading is the design pattern to use, and works great in every other case.  However, if you just delete the “virtual” keyword everything works as intended.

 

 

Written By Steve French

 

Leave a Reply

Your email address will not be published. Required fields are marked *






Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.