0

I want to test methods in my controller, I know about this...

myController = new MyController();

A.CallTo(()=>myController.SomeMethodIWantToTest().Returns(someValueIAmTesting);

The problem is that inside that parameterless constructor, I call numerous methods in other assemblies that set values for private members,

public class MyController : Controller {

    private ILoginBusiness loginBusiness;
    private ISomethingElse somethingElse;
    //... and so on...

    public MyController(){

        loginbusiness = ServiceFactory.GetLoginBusiness();
        somethingElse = //some method in another assembly that initializes the value
        //... and so on, calling methods in other assemblies that initialize   the private members...   

    }

    public ActionResult SomeMethodIWantToTest(){ }

}

So how do I isolate all those method calls in my constructor (so I'm not calling methods in those other assemblies?)

1 Answers1

1

First,

myController = new MyController();
A.CallTo(()=>myController.SomeMethodIWantToTest().Returns(someValueIAmTesting);

Will result in an error, as A.CallTo only handles calls to fakes (and there should be an extra ) after …ToTest()).

Second, the general approach that is taken in this sort of situation is called Dependency Injection. Instead of having a class make all its dependencies (in your case, by calling methods from other assemblies), you have its dependencies provided to it.

Assuming you're able to start injecting dependencies, you're almost home. You're already relying on interfaces inside MyController, so then you can use FakeItEasy to supply fakes to MyController, avoiding calls to the out-of-assembly methods.

Blair Conrad
  • 233,004
  • 25
  • 132
  • 111