Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

How to substitute a Factory-created Singleton object with a Mock object  RSS feed

 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I run into a problem that a cannot solve. I want to test a class which requires a mock object. The problem is the required object is created by a Factory, and to top it all it, it is a Singleton.

I'd better to describe it in details:
My object uses a NetFactory class which creates a Singleton CfgData via a static method. This CfgData should be substituted by a MockCfgData.


Cloud you please give me some advise how to solve this problem?

Thanks in advance.
Peter
 
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you'll need to mock the Singleton, then partially mock the factory so that you can inject the mocked configuration class to return.

Alternatively look at creating a named method in the Singleton that delegates to the factory so you can ignore that factory and simply mock the singleton.
 
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Singletons and mocks usually don't mix very well. If the factory call is a static one, substituting the singleton with a mock may result in unpredictable behaviour if other unit tests use the singleton. This is because subsequent requests for the object will also return the mock.

Of course, the best solution to the problem is to have a factory instance injected in your class, so that you can mock that instance in your test to return your mock config instance.

If that is not possible (and quite often it is not), another simple way to solve the problem is to add a delegating factory method in the class you want to test and then override that method to return the mock in your test case, like this:


This approach has proved to be quite useful in several cases when you need to mock an object which isn't injected to your class.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!