Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mocking a session object

 
Prabhudatta Choudhury
Greenhorn
Posts: 20
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 7466
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic