Which is better, Java reflection or extend class in test





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







2















Have a Java class for which, I am trying to write a JUnit test.



Using JaCoCo to monitor code coverage. Hence, need to call private methods as well from test class.



To call main method and private methods from test class using Java reflection.



My question is extending the main class (Example) in test class better or using java reflection to access the private methods? Currently I am using the reflection as below.



Is it even a good practice to extend the Java class in test class?

I am new to writing test class hence, the question. I would appreciate your help on this.



public class Example { 
public static void main(String s) {
method1();
method2();
..........
}

private Employee method1(String str) {
.........
}

private Employee method2(String str1) {
.........
}
}

public class ExampleTest {
@InjectMocks
Example example;
.....

@Before
public void setUp() {
........
}
@Test
public void testMain() {
try {
String addresses = new String{};
Example loadSpy = spy(example);
loadSpy.main(addresses);
assertTrue(Boolean.TRUE);
} catch (.. e) {
.......
}
assertTrue(true);
}
@Test
public void testMethod1() {
try {
Method method = example.getClass().getDeclaredMethod("method1", String.class);
method.setAccessible(true);
method.invoke(example, "1111");
} catch (Exception e) {
.....
}
assertTrue(true);
}

@Test
public void testMethod1() {
try {
Method method = example.getClass().getDeclaredMethod("method2", String.class);
method.setAccessible(true);
method.invoke(example, "1111");
} catch (Exception e) {
.....
}
assertTrue(true);
}
}









share|improve this question




















  • 4





    What is the reason that private methods need to be called? If the methods need to be used by an external client, even a test case, is it possible that the visibility of the methods should not be private? I.e. protected or public.

    – Justin Albano
    Jan 4 at 14:36






  • 2





    This question is highly opinion based. By in my experience best is to not call private methods, but to design your tests by using public methods only.

    – Bojan Trajkovski
    Jan 4 at 14:37











  • Totally agree with @BojanTrajkovski - the test cases of public methods should cover all the paths hidden in the private methods. If it is not possible, then the code is wrong. If it is hard to achieve - maybe the code is to complicated.

    – h__
    Jan 4 at 14:41











  • Thanks, for your responses. It is already existing code. Don't want to refactor much to implements tests. The methods have try/catch to handle exceptions. That code is not covered hence, have to call the private methods. As suggested will make them public instead of using reflection. Thanks, again to all.

    – opai
    Jan 4 at 14:53


















2















Have a Java class for which, I am trying to write a JUnit test.



Using JaCoCo to monitor code coverage. Hence, need to call private methods as well from test class.



To call main method and private methods from test class using Java reflection.



My question is extending the main class (Example) in test class better or using java reflection to access the private methods? Currently I am using the reflection as below.



Is it even a good practice to extend the Java class in test class?

I am new to writing test class hence, the question. I would appreciate your help on this.



public class Example { 
public static void main(String s) {
method1();
method2();
..........
}

private Employee method1(String str) {
.........
}

private Employee method2(String str1) {
.........
}
}

public class ExampleTest {
@InjectMocks
Example example;
.....

@Before
public void setUp() {
........
}
@Test
public void testMain() {
try {
String addresses = new String{};
Example loadSpy = spy(example);
loadSpy.main(addresses);
assertTrue(Boolean.TRUE);
} catch (.. e) {
.......
}
assertTrue(true);
}
@Test
public void testMethod1() {
try {
Method method = example.getClass().getDeclaredMethod("method1", String.class);
method.setAccessible(true);
method.invoke(example, "1111");
} catch (Exception e) {
.....
}
assertTrue(true);
}

@Test
public void testMethod1() {
try {
Method method = example.getClass().getDeclaredMethod("method2", String.class);
method.setAccessible(true);
method.invoke(example, "1111");
} catch (Exception e) {
.....
}
assertTrue(true);
}
}









share|improve this question




















  • 4





    What is the reason that private methods need to be called? If the methods need to be used by an external client, even a test case, is it possible that the visibility of the methods should not be private? I.e. protected or public.

    – Justin Albano
    Jan 4 at 14:36






  • 2





    This question is highly opinion based. By in my experience best is to not call private methods, but to design your tests by using public methods only.

    – Bojan Trajkovski
    Jan 4 at 14:37











  • Totally agree with @BojanTrajkovski - the test cases of public methods should cover all the paths hidden in the private methods. If it is not possible, then the code is wrong. If it is hard to achieve - maybe the code is to complicated.

    – h__
    Jan 4 at 14:41











  • Thanks, for your responses. It is already existing code. Don't want to refactor much to implements tests. The methods have try/catch to handle exceptions. That code is not covered hence, have to call the private methods. As suggested will make them public instead of using reflection. Thanks, again to all.

    – opai
    Jan 4 at 14:53














2












2








2








Have a Java class for which, I am trying to write a JUnit test.



Using JaCoCo to monitor code coverage. Hence, need to call private methods as well from test class.



To call main method and private methods from test class using Java reflection.



My question is extending the main class (Example) in test class better or using java reflection to access the private methods? Currently I am using the reflection as below.



Is it even a good practice to extend the Java class in test class?

I am new to writing test class hence, the question. I would appreciate your help on this.



public class Example { 
public static void main(String s) {
method1();
method2();
..........
}

private Employee method1(String str) {
.........
}

private Employee method2(String str1) {
.........
}
}

public class ExampleTest {
@InjectMocks
Example example;
.....

@Before
public void setUp() {
........
}
@Test
public void testMain() {
try {
String addresses = new String{};
Example loadSpy = spy(example);
loadSpy.main(addresses);
assertTrue(Boolean.TRUE);
} catch (.. e) {
.......
}
assertTrue(true);
}
@Test
public void testMethod1() {
try {
Method method = example.getClass().getDeclaredMethod("method1", String.class);
method.setAccessible(true);
method.invoke(example, "1111");
} catch (Exception e) {
.....
}
assertTrue(true);
}

@Test
public void testMethod1() {
try {
Method method = example.getClass().getDeclaredMethod("method2", String.class);
method.setAccessible(true);
method.invoke(example, "1111");
} catch (Exception e) {
.....
}
assertTrue(true);
}
}









share|improve this question
















Have a Java class for which, I am trying to write a JUnit test.



Using JaCoCo to monitor code coverage. Hence, need to call private methods as well from test class.



To call main method and private methods from test class using Java reflection.



My question is extending the main class (Example) in test class better or using java reflection to access the private methods? Currently I am using the reflection as below.



Is it even a good practice to extend the Java class in test class?

I am new to writing test class hence, the question. I would appreciate your help on this.



public class Example { 
public static void main(String s) {
method1();
method2();
..........
}

private Employee method1(String str) {
.........
}

private Employee method2(String str1) {
.........
}
}

public class ExampleTest {
@InjectMocks
Example example;
.....

@Before
public void setUp() {
........
}
@Test
public void testMain() {
try {
String addresses = new String{};
Example loadSpy = spy(example);
loadSpy.main(addresses);
assertTrue(Boolean.TRUE);
} catch (.. e) {
.......
}
assertTrue(true);
}
@Test
public void testMethod1() {
try {
Method method = example.getClass().getDeclaredMethod("method1", String.class);
method.setAccessible(true);
method.invoke(example, "1111");
} catch (Exception e) {
.....
}
assertTrue(true);
}

@Test
public void testMethod1() {
try {
Method method = example.getClass().getDeclaredMethod("method2", String.class);
method.setAccessible(true);
method.invoke(example, "1111");
} catch (Exception e) {
.....
}
assertTrue(true);
}
}






java junit4






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 4 at 15:03









Karol Dowbecki

26.9k93860




26.9k93860










asked Jan 4 at 14:33









opaiopai

286




286








  • 4





    What is the reason that private methods need to be called? If the methods need to be used by an external client, even a test case, is it possible that the visibility of the methods should not be private? I.e. protected or public.

    – Justin Albano
    Jan 4 at 14:36






  • 2





    This question is highly opinion based. By in my experience best is to not call private methods, but to design your tests by using public methods only.

    – Bojan Trajkovski
    Jan 4 at 14:37











  • Totally agree with @BojanTrajkovski - the test cases of public methods should cover all the paths hidden in the private methods. If it is not possible, then the code is wrong. If it is hard to achieve - maybe the code is to complicated.

    – h__
    Jan 4 at 14:41











  • Thanks, for your responses. It is already existing code. Don't want to refactor much to implements tests. The methods have try/catch to handle exceptions. That code is not covered hence, have to call the private methods. As suggested will make them public instead of using reflection. Thanks, again to all.

    – opai
    Jan 4 at 14:53














  • 4





    What is the reason that private methods need to be called? If the methods need to be used by an external client, even a test case, is it possible that the visibility of the methods should not be private? I.e. protected or public.

    – Justin Albano
    Jan 4 at 14:36






  • 2





    This question is highly opinion based. By in my experience best is to not call private methods, but to design your tests by using public methods only.

    – Bojan Trajkovski
    Jan 4 at 14:37











  • Totally agree with @BojanTrajkovski - the test cases of public methods should cover all the paths hidden in the private methods. If it is not possible, then the code is wrong. If it is hard to achieve - maybe the code is to complicated.

    – h__
    Jan 4 at 14:41











  • Thanks, for your responses. It is already existing code. Don't want to refactor much to implements tests. The methods have try/catch to handle exceptions. That code is not covered hence, have to call the private methods. As suggested will make them public instead of using reflection. Thanks, again to all.

    – opai
    Jan 4 at 14:53








4




4





What is the reason that private methods need to be called? If the methods need to be used by an external client, even a test case, is it possible that the visibility of the methods should not be private? I.e. protected or public.

– Justin Albano
Jan 4 at 14:36





What is the reason that private methods need to be called? If the methods need to be used by an external client, even a test case, is it possible that the visibility of the methods should not be private? I.e. protected or public.

– Justin Albano
Jan 4 at 14:36




2




2





This question is highly opinion based. By in my experience best is to not call private methods, but to design your tests by using public methods only.

– Bojan Trajkovski
Jan 4 at 14:37





This question is highly opinion based. By in my experience best is to not call private methods, but to design your tests by using public methods only.

– Bojan Trajkovski
Jan 4 at 14:37













Totally agree with @BojanTrajkovski - the test cases of public methods should cover all the paths hidden in the private methods. If it is not possible, then the code is wrong. If it is hard to achieve - maybe the code is to complicated.

– h__
Jan 4 at 14:41





Totally agree with @BojanTrajkovski - the test cases of public methods should cover all the paths hidden in the private methods. If it is not possible, then the code is wrong. If it is hard to achieve - maybe the code is to complicated.

– h__
Jan 4 at 14:41













Thanks, for your responses. It is already existing code. Don't want to refactor much to implements tests. The methods have try/catch to handle exceptions. That code is not covered hence, have to call the private methods. As suggested will make them public instead of using reflection. Thanks, again to all.

– opai
Jan 4 at 14:53





Thanks, for your responses. It is already existing code. Don't want to refactor much to implements tests. The methods have try/catch to handle exceptions. That code is not covered hence, have to call the private methods. As suggested will make them public instead of using reflection. Thanks, again to all.

– opai
Jan 4 at 14:53












2 Answers
2






active

oldest

votes


















5














Do not use reflection to test private methods, it is better to test these methods through the use of the public methods.



So in this case use Example.main() to test the underlying methods.






share|improve this answer

































    1














    Ideally you would refactor the code to extract private methods that need their own testing into new public methods in new classes. If a functionality requires a separate test it often qualifies as something public.



    Other than using reflection, you can change the visibility of these methods to default level and they will be accessible to tests in the same package.



    public class Example { 

    Employee method1(String str) {
    ...
    }

    Employee method2(String str1) {
    ...
    }

    }


    public class ExampleTest {

    @Test
    public void testMethod1() {
    new Example().method1(...);
    }

    }





    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54040940%2fwhich-is-better-java-reflection-or-extend-class-in-test%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      5














      Do not use reflection to test private methods, it is better to test these methods through the use of the public methods.



      So in this case use Example.main() to test the underlying methods.






      share|improve this answer






























        5














        Do not use reflection to test private methods, it is better to test these methods through the use of the public methods.



        So in this case use Example.main() to test the underlying methods.






        share|improve this answer




























          5












          5








          5







          Do not use reflection to test private methods, it is better to test these methods through the use of the public methods.



          So in this case use Example.main() to test the underlying methods.






          share|improve this answer















          Do not use reflection to test private methods, it is better to test these methods through the use of the public methods.



          So in this case use Example.main() to test the underlying methods.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 4 at 14:45









          d3jn

          6191715




          6191715










          answered Jan 4 at 14:36









          Chris RomkemaChris Romkema

          5115




          5115

























              1














              Ideally you would refactor the code to extract private methods that need their own testing into new public methods in new classes. If a functionality requires a separate test it often qualifies as something public.



              Other than using reflection, you can change the visibility of these methods to default level and they will be accessible to tests in the same package.



              public class Example { 

              Employee method1(String str) {
              ...
              }

              Employee method2(String str1) {
              ...
              }

              }


              public class ExampleTest {

              @Test
              public void testMethod1() {
              new Example().method1(...);
              }

              }





              share|improve this answer




























                1














                Ideally you would refactor the code to extract private methods that need their own testing into new public methods in new classes. If a functionality requires a separate test it often qualifies as something public.



                Other than using reflection, you can change the visibility of these methods to default level and they will be accessible to tests in the same package.



                public class Example { 

                Employee method1(String str) {
                ...
                }

                Employee method2(String str1) {
                ...
                }

                }


                public class ExampleTest {

                @Test
                public void testMethod1() {
                new Example().method1(...);
                }

                }





                share|improve this answer


























                  1












                  1








                  1







                  Ideally you would refactor the code to extract private methods that need their own testing into new public methods in new classes. If a functionality requires a separate test it often qualifies as something public.



                  Other than using reflection, you can change the visibility of these methods to default level and they will be accessible to tests in the same package.



                  public class Example { 

                  Employee method1(String str) {
                  ...
                  }

                  Employee method2(String str1) {
                  ...
                  }

                  }


                  public class ExampleTest {

                  @Test
                  public void testMethod1() {
                  new Example().method1(...);
                  }

                  }





                  share|improve this answer













                  Ideally you would refactor the code to extract private methods that need their own testing into new public methods in new classes. If a functionality requires a separate test it often qualifies as something public.



                  Other than using reflection, you can change the visibility of these methods to default level and they will be accessible to tests in the same package.



                  public class Example { 

                  Employee method1(String str) {
                  ...
                  }

                  Employee method2(String str1) {
                  ...
                  }

                  }


                  public class ExampleTest {

                  @Test
                  public void testMethod1() {
                  new Example().method1(...);
                  }

                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 4 at 14:38









                  Karol DowbeckiKarol Dowbecki

                  26.9k93860




                  26.9k93860






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54040940%2fwhich-is-better-java-reflection-or-extend-class-in-test%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Mossoró

                      Error while reading .h5 file using the rhdf5 package in R

                      Pushsharp Apns notification error: 'InvalidToken'