• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Mocking a session object

 
Greenhorn
Posts: 20
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic