How can I unit test void functions?

后端 未结 4 1547
梦毁少年i
梦毁少年i 2020-12-02 02:38
class Elephant extends Animal {   
    public Elephant(String name) {
        super(name);
    }

    void makeNoise() {
        logger.info(\" Elephant  make Sound\         


        
4条回答
  •  一整个雨季
    2020-12-02 03:10

    To test any method, the responsibility to be tested must be visible from the out side of the method by changing state of any variable.

    Typically it is done by returning value from the method. But without that, it can be done in many ways by modifying something from outside of the method scope, in case you have any "problem" to return something from the method!

    In your case, you only log some message. And your code is not really testable in a sense that it does not do something that is directly related to changing the state of any variable (Because you change the state of other resource other than variable, that is not directly accessible by your code. You have to write some code to read the changes from that external resource, hence makes your testing code dependent to the reading also. If you have some problem with reading, your test case will not pass and that does not go with the spirit of the unit testing. The main idea is to reduce the dependency on external codes or libraries as much as possible). But your code can be testable by doing a slight refactoring / shifting responsiblity like below:

    String makeNoise() {
        return "Elephant  make Sound";
    }
    
    String perform(String day) {
        if (day.equals("thursday") || day.equals("friday")) {
          return makeNoise();
        }
    }
    

    And then you shift the responsibility of logging the value returned from perform method to the one using it like below:

     logger.info(perform(day));
    

提交回复
热议问题