0

I am writing a set of API tests using Codeception and one of the methods I would like to have on every single test looks like:

public function ActionWasNotDoneIfParamsAreMissing(ApiTester $I): void
{
    $url = $this->serviceUrl;
    $method = $this->method;

    $dataCombination = $I->pcArrayPowerSet($this->data);
    foreach ($dataCombination as $combination) {
        $I->seeExceptionThrown(
            BadRequestHttpException::class,
            static function () use ($I, $url, $combination) {
                $I->$method($url, $combination);
            }
        );
    }
}

I did read docs here and here but is not so clear to me how to achieve re-usability in this scenario.

I wonder if there is a way to add this as part of a Helper so it can be reuse at any single test without the need to repeat the code. Any ideas and/or help?

1 Answer 1

1

I have got my answer here. Here are the steps I have followed:

  • Create the StepObject class by running the command:

    php vendor/bin/codecept generate:stepobject api CommonTest
    
  • Adjust the method as follow:

    public function checkIfHttpMethodIsNotAccepted(
        string $serviceUrl,
        array $notAllowedMethod = [],
        array $data = []
    ): void {
        $I = $this;
        foreach ($notAllowedMethod as $method) {
            $I->seeExceptionThrown(
                BadRequestHttpException::class,
                static function () use ($I, $serviceUrl, $method, $data) {
                    $I->$method($serviceUrl, $data);
                }
            );
        }
    }
    
  • Call the new method from the test class:

    public function ActionWasNotDoneIfHttpMethodIsNotAccepted(Step\Api\CommonTest $I): void
    {
        $I->checkIfHttpMethodIsNotAccepted(
            $this->serviceUrl, 
            self::$notAllowedMethod, 
            $this->data
        );
    }
    

From now on I just have to do the last on my test classes and not repeat the code all over the places. Hope it help someone!

Note: If for some reason you got errors run the command php vendor/bin/codecept build before run any test suite.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.