Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write tests to test functions with variable return values?

I've got a simple function like this:

    function CreateFileLink()
    {
            global $Username;

            return date("d-m-y-g-i");
    }

How do you write code to test a function like that where the return data is variable?

like image 462
GeoffreyF67 Avatar asked Mar 09 '26 05:03

GeoffreyF67


2 Answers

You could test it if you could somehow get control over that date() function. For example, in this case, you only care that the date function is being called with "d-m-y-g-i"; you don't really care about the output of it. Maybe something like:

function CreateFileLink(DateProvider dateProvider)
{
        global $Username;

        return dateProvider.date("d-m-y-g-i");
}

Sorry, I don't even know what language this is but hopefully you can see my point. In production code, you'd call this by doing:

DateProvider standardDateProvider = new DateProvider() { Date date(String str) { return date(str); } };
CreateFileLink(standardDateProvider);

But in your test, you can provide an alternate implementation that will throw an error if the input isn't what you expect:

DateProvider mockProvider = new DateProvider() 
{
    Date date(String str) 
    {
        if(str != "d-m-y-g-i") throw Exception();
        return "success";
    }
}
like image 61
Outlaw Programmer Avatar answered Mar 11 '26 07:03

Outlaw Programmer


What your unit tests need to do is setup the environment for this function to work properly, in other words, you simulate as if the system was running by setting up other variables, then you SHOULD be able to know what it will return based on how your unit test set up these variables (unless of course the return value is a random number, in which case all you could do, as Randolpho suggested, is make sure it doesn't throw).

If your unit tests is found in this situation of setting up and calling a whole bunch of other methods just to test this function, it's probably a good indication that your function is tightly coupled and you could probably break it down into smaller pieces.

like image 34
Ricardo Villamil Avatar answered Mar 11 '26 05:03

Ricardo Villamil