开发者

Moq and Concrete Dependencies in ASP.NET MVC 2

I'm working on an ASP.NET MVC 2 project. I've been handed a few controller classes with a tight dependency on a data repository class, something like this:

public class MyController : Controller
{
  MyRepository myRepository = new MyRepository();
  // ...
}

Class MyRepository is concrete, not an interface.

Basically, while I have read access to this code I don't have write access. I'm trying to write some unit tests to make sure it works. Needless to say I don't want to have the actual database get hit as I do this, so clearly some sort of mocking is in order.

I'm fairly new to unit testing and mocking, but I've read up on Moq and I think I get the basic idea of how it works. I've been able to successfully create a simple mock repository object... but the problem is, I still don't know how to pass it into the class!

If I'd written the original code I would have used an interface rather than a concrete class, and I would have written an extra constructor for开发者_StackOverflow dependency injection. As it is, I'm in a mess.

Can Moq help me pass it into the class (if I mock MyController), or do I need to petition for write access so I can refactor?


I would recommend you to ask write access and change the code to use constructor injection. Everything else would be hacks which won't bring much value to this code. As long as a class has strong coupling with some other class it is close to impossible to unit test and even if you find some method this test will be so brittle that it would be a waste of time.


You are correct in that to do this properly you need to have a public way of injection your own mock of the repository. Moq will not help you here. You should try to change the MyController code to enable this kind of dependecny injection.

If you cannot chagne the code, you could always change things using private reflection. But doing this fragile because a change in the controllers implementation can break your tests.

Of course, then you need to figure out how to mock the repository. If it was not designed for mocking then something like Moles could work

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜