3

I am trying to write a unit test for a controller that has a dependency on a type whose lifestyle is "PerWebRequest".

Castle throws the following exception:

System.InvalidOperationException: HttpContext.Current is null. PerWebRequestLifestyle can only be used in ASP.Net.

Can I mock the HttpContext.Current property somehow to get around this?

I have tried to use MVCContrib's TestControllerBuilder to initialize this controller but it has no effect.

  SymptomTopicController controller = new SymptomTopicController();
        controller.WorkOrderFulfillment = workOrderFulfillment;

        TestControllerBuilder controllerBuilder = new TestControllerBuilder();
        controllerBuilder.InitializeController(controller);
Nick
  • 19,198
  • 51
  • 185
  • 312

2 Answers2

7

You're doing it wrong

Abstract the dependency and don't use container in your tests.

Krzysztof Kozmic
  • 27,267
  • 12
  • 73
  • 115
  • 1
    The dependency is abstracted.. the controller dependencies are resolved by injection. The question is how to mock HTTPContext not how to write unit tests. – Nick Jan 06 '11 at 15:30
  • The dependency is obviously not abstracted (enough). If it was you would not need to use HTTPContext in your test because controller would not have any hard dependency on it, and the way you describe it, it does in your case, meaning it's not abstracted. – Krzysztof Kozmic Jan 06 '11 at 21:40
1

Have you seen this question: Mock HttpContext.Current in Test Init Method ?

Community
  • 1
  • 1
Victor Haydin
  • 3,518
  • 2
  • 26
  • 41