It's not a secret anymore!
The moose likes Testing and the fly likes mock javax.naming.InitialContext Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » Testing
Bookmark "mock javax.naming.InitialContext" Watch "mock javax.naming.InitialContext" New topic

mock javax.naming.InitialContext

zb cong
Ranch Hand

Joined: Jan 14, 2002
Posts: 416

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?
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33107

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.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
zb cong
Ranch Hand

Joined: Jan 14, 2002
Posts: 416
yes, i want to test my source code by junit out of the container.
Raja Pal
Ranch Hand

Joined: Jul 12, 2004
Posts: 92
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).

Java Pal - Your friend in technology and innovation...India.
I agree. Here's the link:
subject: mock javax.naming.InitialContext
It's not a secret anymore!