I am testing Account Controller in asp.net mvc project. I tested all methods and I looked the code coverage results, I noticed the Initialize method is not coveraged.
How can I test this method?
public class AccountController : Controller
{
public IFormsAuthenticationService FormsService { get; set; }
public IMembershipService MembershipService { get; set; }
protected override void Initialize(RequestContext requestContext)
{
if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
base.Initialize(requestContext);
}
I tried this test method but error occured.
[TestMethod]
public void Constructor_ReturnsController()
{
RequestContext requestContext = new RequestContext(new MockHttpContext(), new RouteData());
AccountController controller = new AccountController
{
FormsService = null,
MembershipService = null,
Url = new UrlHelper(requestContext),
};
IController cont = controller;
cont.Execute(requestContext);
}
Error Message:
Test method MVC3Project.Tests.Controllers.AccountControllerTests+AccountControllerTest.Constructor_ReturnsController threw exception:
System.NotImplementedException: The method or operation is not implemented.
You will need to invoke it explicitly in your unit test:
Note that using the
Initializemethod to setup your dependencies is bad practice. I would recommend you using dependency injection:Now you could setup your favorite dependency injection framework to inject those dependencies into your controller. For example with Ninject that’s pretty easy. Install the
Ninject.MVC3NuGet and then inside the generated~/App_Start/NinjectWebCommon.csfile configure the kernel:and finally you could mock those dependencies into your unit test and then define expectations on them.