c# - How to pass a Dependency from a Test Project to a Concrete Implementation in DryIoc -
i'm sorry don't have code share because i'm not sure how work.
i have test project called api.tests , i'm writing tests newscontroller within api project. i'm not sure how pass dependency tests api since it's one-way reference.
newscontroller
private igetnews _getnews; private iaddnews _addnews; private iloggingservice _log; public newscontroller() { _getnews = registerdependencies.container.resolve<igetnews>(); _addnews = registerdependencies.container.resolve<iaddnews>(); _log = registerdependencies.container.resolve<iloggingservice>(); }
your current code using service locator anti-pattern. makes controller tightly coupled dependencies , difficult test in isolation. need invert dependencies. (ie: dependency inversion)
refactor controller use explicit dependencies via constructor injection.
public class newscontroller { private readonly igetnews getnews; private readonly iaddnews addnews; private readonly iloggingservice log; public newscontroller(igetnews getnews, iaddnews addnews, iloggingservice log) { this.getnews = getnews; this.addnews = addnews; this.log = log; } //...other code }
for unit testing can mock , inject dependencies subject under test. following example uses mocking framework (moq) mock dependencies , inject them subject under test
public void examplenewscontrollertest() { //arrange var getnews = mock.of<igetnews>(); var addnews = mock.of<iaddnews>(); var log = mock.of<iloggingservice>(); var subject = new newscontroller(getnews, addnews, log); //act //...exercise method under test subject.someaction(); //assert //...assert subject behaves expected. }
you configure dependencies suit test case/scenario.
Comments
Post a Comment