简体   繁体   中英

Why is it considered a bad practice to test a class by extending it?

As far as I understand, there are two main methods to test a class.

  1. test class to extend the class under test
  2. test class to create the class under test (composition)

As far as I can tell, the first method is considered to be a bad practice.

but why is that?

For me, Unit Test have 2 main purposes:

  1. verify the testobject is doing what I expect it to do
  2. document how to use the tested class correctly

By extending the tested class, the test seams likely to change the classes behaviour. This is bad practic for testing. Sometimes I even do it to fix for example current time dependency like this if DI is no option:

   private InstanceToTest instance;
   private Calendar now = new GregorianCalendar(2019, 4, 4, 13, 23, 47);
   @Before
   public void initInstance() {
      instance = new InstanceToTest() {
         @Override
         Calendar getNow() {
            return now;
         }
      };
   }

Now I can test against 4th of April 2019, 13:23:47 to make the test stable.

Sometimes I want to test extracted inner methods separately. I prefer to make these method package private. This way I can call them from my test (if it's in the same package whithin the test source folder) without overwriting them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM