开发者

How should I implement unit testing when working with Repositories, Unit of Work, and Services?

my Controllers usually consume one or two Services. In turn, I inject a same Unit of Work to these Services to use the same Context. That is:

开发者_高级运维
public class TestController : Controller
{
    private UnitOfWork _unitOfWork;
    private Service1 _service1;
    private Service2 _service2;

    public TestControler()
    {
        _unitOfWork = new UnitOfWork();

        // here I inject the unit of work to the services.
        _service1 = new Service1(_unitOfWork);
        _service2 = new Service2(_unitOfWork);
    }
}

My questions:

  1. How should I implement unit testing? Should I inject the unit of work only, or unit of work and services too?
  2. How can I dispose the objects? Should I dispose the unit of work or the services (which in turn dispose the unit of work)?


1.) all dependencies should be injected, so anything you are newing up in the controller, which for you would be your unit of work and two services. this will make testing work properly, as you'll be able to mock all dependencies. actually, looking at it more, you shouldn't be injecting the unitofwork class, as it is only a dependency of the services.

2.) your services shouldn't need disposing if the unit of work object is actually handling all the work. my suggestion would be to implement idisposable on the UnitOfWork class and put it in a using()


Generally, you want to isolate whatever you're testing as much as you can. So if you're testing your controller, the only "real" object should be your controller. This way you can have your mocked service/repository return controlled/ known things from its actions and/or make sure your controller is calling the right things on it.

if you don't do that, then your unit test is more of an integration test, whcih ensures that several 'live' objects work together as planned.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜