简体   繁体   中英

What is the correct way of testing a class without adding fields that are only used in testing?

I've designed a very simple disk based hash table. I've already tested it and the number of collisions is theoretically correct, but the test involved adding a field to the class that is incremented when there is a collision during the retrieval of an entry and checking at the end that the number of collisions is conformant. This counter is completely useless in the real class, so I'm asking if there is a smarter way to test the class without adding fields that are not needed outside JUnit tests. What is the best practice in this case?

More specifically, I can write a mock-up of my class:

public class HashTable {
  //some fields here
  
  int collisions_counter = 0; //this is only needed for testing! useless otherwise

  //some methods here
  
  public TableEntry get(Key key) {
    //code to find the entry 
    if (collisions)
      collisions_counter++;

    //code to return the entry
  }
}

This is very messy because if I want to change the collision resolution strategy or the hash function I need to add manually the field to the class and rewrite the logic to count the collisions, test the class and then remove the field because I don't need it in the final working class.

What if you were to use dependency injection ? As far as I understand it, your hash table algorithm depends on disk operations. I don't know your solution, but I assume you write or read from the disk. If you abstract these operations away (eg by using an interface), you can inject the dependecy into your hash table solution (eg through the constructor). In the main code, you can inject the real disk based implementation. But when you test it, you can inject a mock (either your own mock or one from a library like Mockito) instead, and use the mock to assert the number of times it has been called.

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