Java tool for testing private methods?

前端 未结 5 2068
忘了有多久
忘了有多久 2021-02-20 10:32

There are different opinions on the meaningfulness of testing of private methods, e.g., here and here. I personally think it makes sense, the question is how to do it properly.

5条回答
  •  半阙折子戏
    2021-02-20 11:15

    it would be nice to be able to call private methods in the test code like

    @MakeVisibleForTesting Something something = new Something();
    Assert.assertEquals(43, something.internalSecret());
    

    There's such thing as a method annotation, check out dp4j's @TestPrivates:

    @Test
    @TestPrivates 
    //since the method is annotated with JUnit's @Test this annotation is redundant. 
    // You just need to have dp4j on the classpath.
        public void somethingTest(){
          Something something = new Something();
          int sthSecret = something.internalSecret();
           Assert.assertEquals(43, sthSecret); //cannot use something.internalSecret() directly because of bug [dp4j-13][2] 
        }
    

提交回复
热议问题