I've got a form class, and I'm injecting my custom functionality class into it via constructor. That class is added to the container via the services.yml
file defined in my custom module.
I'd like to test that the form is functioning correctly, but for testing purposes I'd like to replace the class that's injected into the form with a fake one.
Both real and fake classes implement the same interface. The form is working with that interface.
My test file:
<?php
/**
* @file
* Contains \Drupal\my_module\Tests\FormTest.
*/
namespace Drupal\my_module\Tests;
use Drupal\my_module\Tests\Fake\FakeClass;
use Drupal\simpletest\WebTestBase;
class FormTest extends WebTestBase
{
public static $modules = [
'my_module',
];
public function setUp()
{
parent::setUp();
$fake = new FakeClass();
$this->container->set('my_module.real_class', $fake);
// $this->container->get('my_module.real_class') returns a FakeClass object.
}
public function testFormWorks()
{
$this->drupalGet('my-form');
$this->drupalPostForm(NULL, [], 'Submit');
$this->assertRaw('Form is working.');
}
}
When I'm running the test, the real class is being used, which is not the desired test behaviour.
I can't figure out what I'm doing wrong here. Any help is appreciated.
Update: the issue is not specific to forms. Same thing happens in page controllers.