unit-testingasp.net-mvc-2moqninjectninject-2

Mocking a datacontext for an object that has a dependency


I'm writing some unit tests in my project and I have a datacontext dependency on the controller containing the methods I'd like to test.

I'm using Ninject to inject the dependency and Moq to create my mock datacontext. My DI makes use of an interface IDataContext which my dbml impliments and is used through out the injection process.

In my unit test I'm creating my mock datacontext as follows:

var mock = new Mock<IDataContext>();
var myController = new MyController(mock.Object);

This throws a Object reference not set to an instance of an object. exception on the second line whilst executing the datacontexts constructor.

I'm clearly missing a fundamental piece in setting this up however most of the Moq examples I've seen involve some kind of test against the mocked object using Setup().

Am I going about this the right way? Should I be creating a mock of my IDataContext interface or something else?


Solution

  • haha, the answer came while i was reading through emad's blog on unit testing in ASP.Net MVC.

    I'm guessing that you didn't add the connection string to the app.config of your test project right? :)

    And that's the database dependency way because you're still not mocking the database end. So if you want to do that, you need to google up for some codes, there are a few ways to do that.

    i find these few references below to be quite useful, but since i don't really have a need to mock the database end, i'm just using my test DB server for now.

    link