Question

I have several Windsor Installers at my ASP.NET MVC application. They register controllers and services. Most of them depend on ICurrentService.

Controller example:

public DataStructureController(
            IMapper mapper,
            DataEntityService dataEntityService,
            FieldDefinitionService fieldDefinitionService,
            CompanyService companyService,
            ICurrentService currentService,
            SelectListService selectListService,
            EnumResourceService enumResourceService,
            WebPreprocessService preprocessService)
            : base(preprocessService)
{
   // Initialise variables code here
}

Service example:

public DataEntityService(DataEntitySpec specification, ICurrentService currentService)
            : base(specification)
{
    // Initialise variables code here
}

In my test classes I have a method, that I call once in [TestInitialize] marked method, or on/many times in [TestMethod] marked methods:

private static ICurrentService MockCurrentUser(User user)
{
    var currentUserSerivceMock = new Mock<ICurrentService>(MockBehavior.Strict);

    currentUserSerivceMock.Setup(x => x.UserId).Returns(user.Id);
    currentUserSerivceMock.Setup(x => x.CompanyId).Returns(user.CompanyProfile.Id);

    return currentUserSerivceMock.Object;
}

I want to replace ICurrentService implementation when calling the container.Resolve<> method, because it depends on HttpContext, that isn't available when unit tests run. Is it possible and how do I do it with minimum code?

Was it helpful?

Solution

You can simply create a fake HttpContext:

HttpContext.Current = new HttpContext(
new HttpRequest(null, "http://tempuri.org", null),
new HttpResponse(null));

And then in your tests:

[SetUp]
public void SetUp()
{
    HttpContext.Current = new HttpContext(
        new HttpRequest(null, "http://tempuri.org", null),
        new HttpResponse(null));
}
[TearDown]
public void TearDown()
{
    HttpContext.Current = null;
}

*Reference: http://caioproiete.net/en/fake-mock-httpcontext-without-any-special-mocking-framework/

OTHER TIPS

Register your implementation as a Fallback with Windsor. Then in your test register your mock instance. That or just build up a dedicated instance of the container for your test and register what you like.

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