Like others, I’m going to use my web log as a pseudo knowledge base.

I ran into an error using xUnit.Net against an ASP.NET MVC project. When trying to get an instance of the DataContext, I’d get an “object reference not found” error.

[Fact] public void InitDb() { AdventureWorksDataContext db = new AdventureWorksDataContext(); }

Error 1 TestCase ‘AdventureWorks.Tests.Controllers.HomeControllerFacts+Index.InitDb’ failed: System.NullReferenceException : Object reference not set to an instance of an object. at AdventureWorks.AdventureWorksDataContext..ctor() in C:\Users\charles.flatt\Documents\Projects and Apps\App - AdventureWorks\src\AdventureWorks\Models\AdventureWorks.designer.cs:line 62

I assumed, ignorantly, that the DataContext would instantiate using the web project’s web.config, and thus the connection string. But the test dll uses its own app.config file and connection strings. On reflection, this makes perfect sense, and is very useful since I can easily test against a different database. The only requirement is to name the connection string the same in the test project’s app.config, as the web project’s web.config.

<add name=“AdventureWorks_DevConnectionString” connectionString=“Data Source=localhost;Initial Catalog=AdventureWorks_Dev;Integrated Security=True” providerName=“System.Data.SqlClient” /> </connectionStrings>