views:

136

answers:

2

I have an ASP.NET MVC application with a separate project added for tests. I know the plusses and minuses of using the connection to the database when running unit tests, and I still want to use it. Yet, every time when I run the tests with the NUnit tool, they all fail due to my Data Context being null. I heard something about having a separate config file for the tests assembly, but i am not sure whether I did it properly, or whether that works at all.

A: 

How are you creating your data context? How is it used in your action? Typically, it will use the database referred to when you set up the classes in the designer so you'd get a context connected to what you used for the designer which is, arguably, not what you want for unit tests, thus you add an app.config file to your unit test project and change the connection string to your test database. It doesn't usually result in a null data context.

I suspect that your unit test is simply not touching the code that creates the data context before you invoke the action method. Without code though, it's really impossible to tell.

tvanfosson
By default, all the tests are done in a separate project which referneces the original project and is compiled as a dll file. That is probably the reason
@user -- yes, but how do you create the context in the controller you are testing? I understand it's a separate project, but the designer usually keeps a default connection string that it uses if no config file is there. In any event, I don't see where the data context would be null -- I could see it throwing an exception if the connection string was null.
tvanfosson
+1  A: 

i think you should check this discussion here, it should be related as i was having the same problem.

and how i solve my problem was just to copy my web config content to the app config inside he test project and voila, database connection restore and all is fine in the land of mvc again.

melaos
Indeed, that's what I did