• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Junit testing with dependencies

 
Pradeep Kumar
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends,
I am a beginner in Junit testing and just started exploring Junit for writing the test cases. I have a scenario where I am struck and finding it difficult to proceed. The scenario is that I am testing a public method which internally calls private methods. In on of the private method, the method tries to connect to the environment and the properties of the environment is fetched in the private method. How can i override the behavior such that I can override the behavior by populating the properties and mimic the environment dependency even though I do not directly call the private method.

Ex:

In the main class:

In the ConfigDetail class



Please let me know to do proceed.
Thanks and Regards,
Pradeep
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34974
379
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pradeep,
You are going to need to refactor that code to make it testable. Ideas:
  • 1) Pass in ConfigDetails so you can make your own - only works if you want to integration test thru to the database
  • 2) Move the private method code to an other class with an interface and mock it out
  • 3) Make the private method default access or protected and override it to do nothing.


  • #3 is often a hack, but it is easiest to do. Especially if you can't change the code much.
     
    Pradeep Kumar
    Ranch Hand
    Posts: 109
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Jeanne Boyarsky wrote:Pradeep,
    You are going to need to refactor that code to make it testable. Ideas:
  • 3) Make the private method default access or protected and override it to do nothing.


  • #3 is often a hack, but it is easiest to do. Especially if you can't change the code much.


    I like the idea of the 3rd option. How do i override the method and test the method. Do you mean extends the class and override the method and test the sub class?
     
    Jeanne Boyarsky
    author & internet detective
    Marshal
    Posts: 34974
    379
    Eclipse IDE Java VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Pradeep Kumar wrote:
    Jeanne Boyarsky wrote:
  • 3) Make the private method default access or protected and override it to do nothing.


  • #3 is often a hack, but it is easiest to do. Especially if you can't change the code much.


    I like the idea of the 3rd option. How do i override the method and test the method. Do you mean extends the class and override the method and test the sub class?

    Exactly!

     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic