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?

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

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

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

Comments

0

In VS 2010, Microsoft Moles is an option for mocking.

In VS 2012, Microsoft Fakes is an option for mocking.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.