mardi 28 novembre 2017

Testing - How this common scenario is classified and handled

I’m just diving into testing/test driven development in php, and am a bit confused about how to handle a very typical scenario in our legacy codebase. Our codebase does not have many classes, it’s very functional programming oriented.

In this example code, which is pseudocode, I want to write a test for getAndOrderUsersByAge(). As you can see it first gets all the users from our database (in a giant array lets say, because we don’t have objects/classes) then sorts them. This is of course a VERY common occurrence in our code, manipulating or analyzing data gotten from the database; not objects, but an array of database rows basically.

Note that I've added an error in the if statement to simulate an error I want my tests to catch.

//gets all users in our db into an array, then sorts them by age
function getAndOrderUsersByAge(){
     //get all users from the db
     $all_users = getAllUsers();

     //sort
     $all_users_sorted = sortUsers($all_users)

     //notice I've made a mistake here on purpose, left the "d" off of "$all_users_sorted"
     //so the function will always return false, a mistake...which I want tests to catch
     if(!empty($all_users_sorte){
         return $all_users_sorted;
     }
     else{
         return false;
     }
}

My questions are:

1.) Is testing the function getAndOrderUsersByAge() unit testing, integration testing, or …?

2.) In my (unit?) test(s) of getAndOrderUsersByAge(), I want to assume that getAllUsers (the function which gets things from the db) behaves correctly because I only want to test getAndOrderUsersByAge() right? I’m not really sure what “concept” this falls under when I’m reading the two books I have on testing. Is this where I would “mock”, e.g. create some fake data for getAllUsers() to return?

3.) What tests would you write for getAndOrderUsersByAge()? I think I would write one that ensures a non-empty array is returned when getAllUsers() returns a non-empty array, as this would catch the error I've created. I'm not sure what else though.

Any tips, recommended reading material, etc. is very welcomed.

Aucun commentaire:

Enregistrer un commentaire