1

I have 1 function that is returning cancel form button. This function is in my .module file.

function _cancel_button(array &$form, FormStateInterface &$form_state) {
  // Adding buttons to cancel form.
  $form['actions']['cancel'] = [
    '#type' => 'submit',
    '#value' => t('Cancel'),
    '#access' => TRUE,
    '#submit' => ['redirectcallback'],
    '#limit_validation_errors' => [],
  ];
  return $form;
}

How to write PHPUnit test for this function? Is is possible to write a test for a function which is not enclosed in any class or don't have any namespace?

  • It is possible in d8 to write hooks in the oop method. So if you will do so you can encapsulate your custom function into a class. – OPTASY Nov 14 '17 at 18:14
0

It is technically possible to write a unit test for this. You'd need to manually require your .module file though.

It might be easier to use a Kernel test, as these will automatically load module files, fire hooks, etc.

MyTest extends KernelTestBase {

  /**
   * Modules to enable.
   */
  public static $modules = ['my_module'];

  /**
   * Test the function.
   */
  public function testCancelButton() {
    // The .module file will already be loaded, so you can call your custom function directly.
    $form = [...];
    _cancel_button($form, ...);
    // Now make assertions about expected changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.