I am working on writing unit tests properly, and I wonder is it bad technique to test the result of a method under test by calling another method to verify the result?
ie. in the below example I can only check that an StoreObject method call was successful(ie. a object being stored in the cache) by calling either FetchObject or the HasCachedObjects property, both of which contain logic that should be tested separately. What would you do in this case where the result is hidden from the public API?
I have a Cache class:
public class Cache {
private Dictionary<string, object> _Cache = null;
public bool HasCachedObjects {
get {
if (_Cache.Count > 0) {
return true;
} else {
return false;
}
}
}
public Cache() {
_Cache = new Dictionary<string,object>();
}
public void StoreObject(string key, object obj) {
_Cache[key] = obj;
}
public object FetchObject(string key) {
if (_Cache.ContainsKey(key)) {
return _Cache[key];
}
return null;
}
}
Don't think of a test case as testing a method; think of it as testing a unit of functionality (or perhaps a use case).
So your test might be StoreObject_WhenSuccessful_AddsToCache or some such.
And yes, I'd confirm the test via the public API.
Not at all. In fact, those are probably two different tests - one to verify that HasCachedObjects is true after caching an object, and one to verify that you can retrieve an object after storing it.
(I'm not really sure what this class does except wrap a Dictionary in a slightly different API, but that's another topic...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With