Suppose I need to add unit tests for the following class from legacy code (that has no unit test for now). It is just a simple map or dictionary.
function Map(...) { ... }
Map.prototype.put = function (key, value) {
// associate the value with the key in this map
}
Map.prototype.get = function (key) {
// return the value to which the specified key is mapped, or undefined
// if this map contains no mapping for the key
}
Map.prototype.equals = function (obj) { ... }
// ... and more bound functions
It seems there is no way to test only one function at a time. You cannot test get() without calling put(), for example. How do I unit test this?
Each method has a contract, explicit or implicit. Map.put() takes some kind of input and mutates something internal or external to Map. In order to test that function, your test needs access to what is mutated. If it is internal and not exposed externally, your test must either exist inside the Map class, the state must be exposed, or the mutateable state structure must be injected into the class in a way that external access remains possible:
ie: