views:

993

answers:

3

I'm just getting started with MSTest (or at least the VS 2008 testing tools, is there a difference?)

I'm wanting to test code that uses a session object. Obviously I don't have an HttpContext and I can't simply create one, so the code fails with a NullReferenceException.

Is this code simply un-testable?

+1  A: 

I don't know about untestable but it's certainly hard to test. You could use typemock, it can create mocks and stubs of virtually everything. But it's not free.

You could also try wrapping the calls to the session stuff inside a separate object and hiding that behind an interface. Then you can inject that interface into your code. For your tests you can inject a mock implementation. This will achieve two things, your code is easier to test and you're no longer tied to the session implementation in Asp.Net.

Mendelt
+1 use separate class. @ilivewithian when configuring dependency injection you can inject HttpContext.Current.Session ... on your test you just pass the mock directly
eglasius
A: 

What level of involvement does the session object play in the logic you want to test? For example if it's just a value that asp.net is using you could implement one of the presentation patterns to abstract this away (and make writing a test easy)

For example -- the below logic would be easy to test by pushing the session info to the view implementation

If UserObject.IsActive() Then
  _View.SessionActive = True
Else
  _View.SessionActive = False
End If
Toran Billups
+1  A: 

I don't know what type of web project (MVC or WebForms) you are trying to test but you should be able to mock out the HttpContextBase class using Scott Hanselmans mock helpers which has examples in Rhino.Mocks and Moq both of which are free.

Jared
That looks exactly like what I need, thanks.
ilivewithian