jeudi 31 décembre 2015

How should I deal with external dependencies in my functions when writing unit tests?

The following function iterates through the names of directories in the file system, and if they are not in there already, adds these names as records to a database table. (Please note this question applies to most languages).

def find_new_dirs():
    dirs_listed_in_db = get_dirs_in_db()

    new_dirs = []
    for dir in get_directories_in_our_path():
        if dir not in dirs_listed_in_db:
            new_dirs.append(dir)

    return new_dirs

I want to write a unit test for this function. However, the function has a dependency on an external component - a database. So how should I write this test?

I assume I should 'mock out' the database. Does this mean I should take the function get_dirs_in_db as a parameter, like so?

def find_new_dirs(get_dirs_in_db):
    dirs_listed_in_db = get_dirs_in_db()

    new_dirs = []
    for dir in get_directories_in_our_path():
        if dir not in dirs_listed_in_db:
            new_dirs.append(dir)

    return new_dirs

Or possibly like so?

def find_new_dirs(db):
    dirs_listed_in_db = db.get_dirs()

    new_dirs = []
    for dir in get_directories_in_our_path():
        if dir not in dirs_listed_in_db:
            new_dirs.append(dir)

    return new_dirs

Or should I take a different approach?

Also, should I design my whole project this way from the start? Or should I refactor them to this design when the need arises when writing tests?

Aucun commentaire:

Enregistrer un commentaire