What's the right way to add a custom Helper method for unit test suite in Codeception?

Viewed 797

I am trying to add a custom helper method to unit test suite, but when running the test I get Fatal error: Uncaught ArgumentCountError: Too few arguments to function error.

This is what I have so far

  1. Adding the method to _support/Helper/Unit.php
  2. Running the build command
  3. Setup actor in suite.yml
  4. Calling the method via the actor
  5. Running test

When I run the test I get:

ArgumentCountError: Too few arguments to function ExampleTest::__construct(), 0

_support/Helper/Unit.php:


namespace Helper;

// here you can define custom actions
// all public methods declared in helper class will be available in $I

class Unit extends \Codeception\Module
{
  public function get_hello()
  {
    return 'Hello';
  }
}

Test method:

public function testMe1(\UnitTester $I)
{
  $hello = $I->get_hello();
  $this->assertEquals(2, $hello);
}
# Codeception Test Suite Configuration

#

# Suite for unit (internal) tests.

class_name: UnitTester
modules:
  enabled:
    - Asserts
    - \Helper\Unit

Why doesn't testme1() accept any arguments? What step am I missing?

2 Answers

Unit tests methods don't get actor passed as a parameter.

You can call them on $this->tester, like in this example

function testSavingUser()
{
    $user = new User();
    $user->setName('Miles');
    $user->setSurname('Davis');
    $user->save();
    $this->assertEquals('Miles Davis', $user->getFullName());

    $this->tester->seeInDatabase('users', ['name' => 'Miles', 'surname' => 'Davis']);
}

Answer from @Naktibalda is correct for integration tests, not for unit tests.

Only way i find to get modul methods in unit tests is using getModule() method:

public function testSomethink()
{
    $this->getModule('Filesystem')->openFile('asd.js');
}

In this way you propably can load custom module too.

If not, and you can reuse some code in unit test, make some parent class for all yout unit tests. Somethink like BaseUnitTest, which extends from Codeception\Test\Unit. And write your reusable code in this class.

Related