In my job I have a small disagreement on whether we should utilize helper functions for making datasets especially in laravel
framework. A sample for the test is:
namespace Tests\MyAppTests;
use PHPUnit\Framework\TestCase;
use Carbon\Carbon;
class MyTest extends TestCase
{
private function makeATwoHourSpan(Carbon $now, &$start, &$end)
{
$start = new Carbon($now);
$start->modify("-1 hour");
$end = new Carbon($now);
$end->modify("+1 hour");
}
public function testSomething()
{
$now=Carbon::now();
$start=null;
$end=null;
this->makeATwoHourSpan($now, $start, $end);
//Rest Of Test Here
}
public function testSomethingElse()
{
$now=Carbon::now();
$start=null;
$end=null;
this->makeATwoHourSpan($now, $start, $end);
//Rest Of Test Here
}
}
The argument that my supervisor says is that using the makeATwoHourSpan
method even though makes the code DRY it does not aid the readability of the test. Also he mentioned that a test should be autonomous and a easy to run as standalone without any helper function except the tools provided from the framework.
So my question is: Should I avoid utilizing "helper" functions especially when I make test data when I make tests, or having a function for data creation makes is the way to go?
1 Answer 1
I think your supervisor is off track, and I think creating helper functions for integration tests is a perfect way to use OO and DRY principles in your test case design. I've made a career of developing integration tests and integration test frameworks, and do this same sort of thing and much more at every job I do. To not extract the duplicate code out of the tests into a shared function would make your tests harder (more expensive) to maintain. What good manager wants to decrease maintainability of source code, rather than increase it?
I might even go a step farther and move makeATwoHourSpan
into a separate class, since odds are good that you will want other utility functions for creating and manipulating dates in your tests.
Explore related questions
See similar questions with these tags.
Assert()
. Business domain-specific helper methods likemakeATwoHourSpan
can be useful, but they don't really have a place in testing harnesses.makeATwoHourSpan
method is "special"? I did not understand what you mean by "helper" function here. It's very common to create a base scenario before running a specific integration test. Otherwise, each integration test will have very long setups, with a lot of duplication among the tests and hard to maintain.