Should I unit test for null values even if it can never happen?



  • Lets say I have an event listener that is called whenever a person has changed their location. Here's some Java code.

    public class LocationManager() {
    //..
    ..
    ..//
    
    public void updateLocationFromGPS(String userID, String locationName) {
        if(userID!=null && locationName!=null) {
            for(LocationChangeCallback callback : locationCallbacks)
            {
                callback.onLocationChange(userID, locationName, EventSource.GPS);
            }
        }
    
        }
    }
    

    And the callback...

    public class Callback implements LocationChangeCallback {
    
    public void onLocationChange(String userID, String locationName, EventSource eventSource) {
    //DO SOME WORK
    
    
    }
    
    }
    

    Where the event is sent and the callback is received are in two different components, hence I will need to unit test them both. Now, knowing that before I call the callback method, I do a null check on the values, and will only send the event if the values are not null.

    Therefore, the values received in the callback will never be null. Is it best practice to add tests to check for null values (and change my code to pass accordingly) in the callback? If so, why?



  • Yes, it is. Because the unit tests are not only for the current version of the code. They are especially for all future versions and if somebody changes the code and does not know what s/he did, the test can fail and tell him that he did something wrong. So you can't say that this will never happen.

    Also unit tests do not only test code, they are documentation too.


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2