Should functions like this have Unit Tests?

Viewed 334

I've written a webapp using PHP and JS that's kind of working now, and decided that I should learn about unit testing and implement it now while cleaning up my code.

I am confused as to what should be unit tested. Every PHPUnit tutorial I've seen tests getters, setters, counts items in arrays. The site I am working on has say a page that displays photos. A user can Like a photo or Add it to his Favorites. PHP is mainly used in the site as an API layer to the clientside running backbone.js.

How should I write unit tests for these functions? A function (shown below) grabs $_GET data sent to it via AJAX and insert some rows into the database. It does not contain any setters, getters, or counts anything and is not a class. Should it even have a unit test?

An example of a unit test that I can write for these functions will be really awesome! :)

/**
 * Create new Set and add item to it
 *  @return  void
 */ 
public function action_create_set() {
    // Get data from user
    $user_id = Input::get('user_id');
    $post_id = Input::get('post_id');
    $set_name = Input::get('set_name');

    // Create new set
    $data = array(
        'user_id' => $user_id,
        'name' => $set_name
    );
    $set_id = DB::table('sets')->insert_get_id($data);

    // Add item to newly created set
    DB::query("INSERT IGNORE INTO posts_sets (post_id, set_id, user_id)
        VALUES ($post_id, $set_id, $user_id)");

    // Change `created_at` & `updated_at` col of 'sets'
    $data = array(
        'created_at' => DB::raw('NOW()'),
        'updated_at' => DB::raw('NOW()')
        );
    DB::table('sets')
        ->where('id', '=', $set_id)
        ->update($data);
}

For this first function, my impression is that a test can be written to check that those 3 variables $user_id, $post_id, $set_name have to contain data. I feel that there should be a test to check that the 2 insert queries work, but I also think that the functions that insert the rows are provided by the PHP framework and have already been thoroughly tested so no further unit testing is required.

Another guess is the test should provide the 3 variables to the function, then check whether the new rows have been inserted into the 2 tables, but wouldnt this be considered an integration test?


Here's a function that takes input from a user via AJAX, then returns the result in JSON format. Should PHPUnit handle this kind of API functions? Or should the unit testing be done on the clientside?

/**
 * Get items Liked by user
 * @return array
 */
public function action_likes() {

    $user_id = Input::get('user_id');

    $likes = DB::table('likes')
                ->join('posts', 'posts.id', '=', 'likes.post_id')
                ->where('likes.user_id', '=', $user_id)
                ->get();

    return json_encode($likes);

}
2 Answers
Related