Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

mock javax.naming.InitialContext

 
zb cong
Ranch Hand
Posts: 416
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

in my source code, including following code:

InitialContext ctx = new InitialContext();
............= (...........)ctx.lookup("java:comp/env/service/someservce");

so i wonder, in my junit test case, how to mock the InitialContext to look up and return a mock service?
Thanks.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 33694
316
Eclipse IDE Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The simple answer is to move new InitialContext(); to someplace you can mock it out. A separate method or a factory would be best.

What do you want the mock initial context to do? Presumably it returns mock resources so this will take additional mock setup.
 
zb cong
Ranch Hand
Posts: 416
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, i want to test my source code by junit out of the container.
 
Raja Pal
Ranch Hand
Posts: 92
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then depending on what service the "service object" provides and how the container's callbacks initialize your service, you may want to create a mock object of the service instance, with all the functionality/initialization without the containers APIs. Let's say you hard-code some service constants/provide some default objects/resources.

Generally Junit is not a framework for mocking container based services(there are a few Xunit f/w's for that). However depending on what service object you are looking up, you may be able to create a custom mock of it, except of-course when the service is doing some sort of marshalling, caching, etc. in which case refactor your design to test the lookup client's own behaviour not the services behaviour(The services unit testcase will take care of that).
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic