Assume I have the following two functions:
function storeObject(object) {
// Connect to database
// Prepare query
// Execute query
}
function retrieveObjectWith(id) {
// Connect to database
// Prepare query
// Execute query
// Parse results
return object;
}
And that I want to write tests to them:
function testStore() {
storeObject(storedObject)
// Connect to mocked database
// Prepare query to retrieve stored object
// Execute query and retrieve stored object
[retrievedObject] should equal [storedObject]
}
function testRetrieve() {
// Connect to mocked database
// Prepare query to store object
// Execute query and store object
retrievedObject(storedObject)
[retrievedObject] should equal [storedObject]
}
I could simplify the second test if I "trusted" the results from the first, like this:
function testRetrieve() {
// Since I have a separate test for storeObject, I can use it here
storeObject(testObject)
retrievedObject = retrieveObjectWithId(testObject.id)
[retrievedObject] should equal [testObject]
}
Question is
Are there any cons of using the storeObject(object)
instead of rewriting its logic inside the test?
Is it considered a bad practice to do this?
retrieveObjectWithId
by callingstoreObject
, because this means that your tests know only the external API of the object(s) being tested, and thus will be much more resistant to structure-only changes as the code matures/evolves. A simple example from Kent Beck's: github.com/KentBeck/TDD-Tyrant/blob/master/src/TyrantTest.java. It is a test for a simple binary DB utility, and he tests theget
operation by doing aput
. – MichelHenrich May 21 '20 at 12:58