How to inject a fake class into container when running WebTestBase tests? 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:

&lt;?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-&gt;container-&gt;set('my_module.real_class', $fake);

        // $this-&gt;container-&gt;get('my_module.real_class') returns a FakeClass object.
    }

    public function testFormWorks()
    {
        $this-&gt;drupalGet('my-form');
        $this-&gt;drupalPostForm(NULL, [], 'Submit');
        $this-&gt;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.
Here's the solution.

Let's say your module A defines a new service.

In order to alter that service, you need to create a separate module B and follow the steps outlined in Overriding the default service class section on https://api.drupal.org/api/drupal/core%21core.api.php/group/container/8.

Make sure to list module A as a dependency in module B info.yml file.

Add both modules to the $modules array in your test class, and everything will work. $this-&gt;container-&gt;set() is no longer needed.

That issue on drupal.org: https://www.drupal.org/node/2700739