ilivewithian
ilivewithian

Reputation: 19692

Mocking objects when using MSTest

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?

Upvotes: 3

Views: 5226

Answers (4)

Denise Skidmore
Denise Skidmore

Reputation: 2416

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

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

Upvotes: 0

Jared
Jared

Reputation: 8590

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.

Upvotes: 3

Toran Billups
Toran Billups

Reputation: 27399

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

Upvotes: 0

Mendelt
Mendelt

Reputation: 37483

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.

Upvotes: 1

Related Questions