How to write phpUnit tests for hook_form_alter? I have 1 function that is returning cancel form button. This function is in my .module file.

function _cancel_button(array &amp;$form, FormStateInterface &amp;$form_state) {
  // Adding buttons to cancel form.
  $form['actions']['cancel'] = [
    '#type' =&gt; 'submit',
    '#value' =&gt; t('Cancel'),
    '#access' =&gt; TRUE,
    '#submit' =&gt; ['redirectcallback'],
    '#limit_validation_errors' =&gt; [],
  ];
  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 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.