permaculture playing cards
The moose likes Testing and the fly likes Mocking a session object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » Testing
Bookmark "Mocking a session object" Watch "Mocking a session object" New topic

Mocking a session object

Prabhudatta Choudhury

Joined: Jul 03, 2009
Posts: 20

Hi, I'm writing Junit test cases for my servlets. I am using Mockito.mock to mock the request and response object. But when I'm creating session object from the mocked request object the value is coming as null. Please let me know how can I get a session object mocked.

[Added code tags - see UseCodeTags]

I tried to debug the same but failed. Is there any other mocking technology available where I can have my session mocked which is safe and useful in MVC/Struts like environment?

Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

I haven't used Mokito, but based on other tools I have used I'd expect that you'd have to configure your mock request object so that when you call getSession() on it it will return the mock session.

A quick search suggests the when() method would be a good place to start looking: something like when(request.getSession()).thenReturn(mockSession);
Junilu Lacar

Joined: Feb 26, 2001
Posts: 6529

This can be a symptom (code smell) that you're loading up your controller with too much logic/responsibility. You should be able to test your core logic without having to depend on the fact that the input values are coming in from an HTTP request. HTTP is a delivery mechanism, an implementation detail. Your core business logic should not be dependent on it. All it should care about is that it does get some values somehow. That's the level at which you should do unit testing. If you're trying to unit test your controller class, then you should go with Matthew's suggestion but apart from that, you probably should look at refactoring your controller class and pushing some responsibilities down to the business layer classes.

Junilu - [How to Ask Questions] [How to Answer Questions]
I agree. Here's the link:
subject: Mocking a session object
It's not a secret anymore!