Question

I am trying to get familiar with TDD concept and wrote a first test that its "act" part looks like this:

repositoryStub = new Mock<IMyRepository>();
var sut = new MyController(repositoryStub.Object);
var result = sut.Index() as ViewResult;

The controller (MyController) that I am instantiating eventually (deep down) uses ConfigurationManager.AppSettings, while creating view model. The instantiation of the controller fails on the line that is trying to read from Web.Config, but, obviously, runs as expected if project is just run from IDE. I am reading a constant from web.config file, which should not affect the test and it wasn't expected that it will fail once called from another (MyProject.Test) project.

My question to you guys is how to overcome this obstacle?

I don't know if it matters here, but just in case, I am using xUnit for TDD. Thanks!

Was it helpful?

Solution

You need to realize that configuration you're using deep down is the same kind of dependency as IMyRepository. You inject repository via abstract contract (interface). Why the same isn't done for configuration? Quick and naive solution would be to create IConfiguration interface and implement it by simply delegating calls to ConfigurationManager. Your constructor would look like this:

public class MyController(IMyRepository repository, IConfiguration configuration)

What does that tell us? Well, not much unfortunately. Fact that controller requires configuration is very vague. Real question is, what's the exact parameter from configuration it needs? You need to identify that very parameter and that's the real dependency you want to inject. Consider:

  • MyController(IMyRepository repository, IConfiguration configuration)
  • MyController(IMyRepository repository, int serviceCallTimeoutSeconds)
  • MyController(IMyRepository repository, string serviceAccessKey)

Which one communicates its purpose better? The more single-feature oriented your controller is, the less parameters it should use. Your problem might not be where you think it is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top