This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes EJB and other Java EE Technologies and the fly likes Mocking injected Dependencies Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "Mocking injected Dependencies" Watch "Mocking injected Dependencies" New topic

Mocking injected Dependencies

Thorsten Mueller

Joined: Dec 19, 2010
Posts: 5
Hi everybody,

Assume I want to test a class like this:

I want to test outside the container and therefore need to mock the dependencyA. What is the common practice to do this? Do you write an additional constructor that passes dependecyA to get access to or are there better ways?

Best Regards

Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33132

The most common approaches are:
  • write a setter
  • write a constructor
  • set the field directly (since it is package private in your example)
  • set the field using reflection

  • [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
    Thorsten Mueller

    Joined: Dec 19, 2010
    Posts: 5
    allright, I think then I take the constructor!

    Thank you!
    I agree. Here's the link:
    subject: Mocking injected Dependencies
    It's not a secret anymore!