Inject service(s) into Drupal unit test? I am writing a unit test upfront for a service that does not exist yet. Let's just say it is called ResponseFormatter.

I want to start adding unit tests for what I expect this service to do. How do I inject it to a UnitTestCase, or reference it?

Example, I am trying to do something like:

class FormatterTest extends UnitTestCase {

  /**
   * @dataProvider responses
   */
  public function testThisWorks($response, $expected) {
    // the following line I want to call a service, 
    // ex. like $this-&gt;responseFormatter-&gt;format($string);
    $clean = html_entity_decode(strip_tags($response));
    $this-&gt;assertEquals($expected, $clean);
  }

  public function responses() {
    return [
      ['not-set', 'not-set'],
      ['&lt;strong&gt;foo&lt;/strong&gt;', 'foo'],
      ['&amp;amp; #93 bar', '&amp; #93 bar'],
    ];
  }
}
If your new service is sufficiently independent (it doesn't have any or many of it own dependencies), then just create it the setUp().  And then if you have dependencies, you set up mocks (also called doubles).  

An example of a this in core is TimeTest::setUp() does:

protected function setUp() {
  parent::setUp();

  $this-&gt;requestStack = $this-&gt;getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')-&gt;getMock();
  $this-&gt;time = new Time($this-&gt;requestStack);
}


A mocked request stack is created, and the setup then directly instantiates the service class being tested (Time() in this case), passing in the mocked dependency to the constructor.

Then assertions in test methods are pretty simple

public function testGetRequestTime() {
  $expected = 12345678;

  $request = Request::createFromGlobals();
  $request-&gt;server-&gt;set('REQUEST_TIME', $expected);

  // Mocks a the request stack getting the current request.
  $this-&gt;requestStack-&gt;expects($this-&gt;any())
    -&gt;method('getCurrentRequest')
    -&gt;willReturn($request);

  $this-&gt;assertEquals($expected, $this-&gt;time-&gt;getRequestTime());
}


The mock simulates what the service's dependency would do, and then the service method is invoked directly.

If your service has a lot of dependencies, or mocking them is hard, then you should do a KernelTest instead of a TestCase or UnitTest.  However, that may be an indication that your service is too complicated and needs to be broken up (I am also having a problem thinking of a core service that is kernel tested and not unit tested).