views:

83

answers:

3

Hi,

I am working on an ASP.NET WebForm application using MVP pattern. For every Web Form, there is a Presenter class associated to handle UI and Business logic. However, I had problem when writing unit tests for Presenters, since session values are used in presenters. And there is no HTTP context exists during execution of the unit test ( BTW I use nUnit ), making it is impossible to write unit test for presenters.

Anyone can explain how to unit test these presenters?

Thanks

+1  A: 

you can either mock or stub out an IHttpContext and let your framework inject the real HttpContext or you can wrap the session, cookie, ... state behind some interfacing, or you could use "Moles" from Pex, the interfacing is explained here http://haacked.com/archive/2007/09/09/ihttpcontext-and-other-interfaces-for-your-duck-typing-benefit.aspx

Tim Mahy
+1  A: 

You can change your Presenter class to have a dependency on HttpContextBase. Once that is done, you can supply a mocked version of the HttpContext to your presenter class for testing. In production, you would simply supply the HttpContext.Current property.

pattersonc
A: 

Hm, I would suggest another approach. I think your presenter should not be aware of HttpContext, PageLifeCycle etc. because you have to test it in isolation. So rather than trying to mock IHttpContext, try to extract values that you need in presenter(you don't need whole httpcontext object right, just some values from session, cookies etc) and inject in presenter through presenter constructor. Now you can test it properly.

Cheers

Marko