1

I have the following code that throws catch an exption:

  public function deliverPrintable(array $entities, PrintEngineInterface $print_engine, $force_download = FALSE, $use_default_css = TRUE) {
    try {
      $renderer = $this->prepareRenderer($entities, $print_engine, $use_default_css);
    } catch (\InvalidArgumentException $e) {
      watchdog_exception('entity_print', $e);
      return FALSE;
    }
  }

The test below will fail because it's expecting an exception to be thrown:

  /**
   * Test that you must pass at least 1 entity.
   *
   * @covers ::deliverPrintable
   * @expectedException \InvalidArgumentException
   * @expectedExceptionMessage You must pass at least 1 entity
   */
  public function testNoEntities() {
    $print_engine = $this->container->get('plugin.manager.entity_print.print_engine')->createInstance('testprintengine');
    $this->container->get('entity_print.print_builder')->deliverPrintable([], $print_engine, TRUE);
  }

I took out the exception part of the method and left and just tested the returned value. But I would like to test that an exception have been logged is this possible?

  /**
   * Test that you must pass at least 1 entity.
   *
   * @covers ::deliverPrintable
   */
  public function testNoEntities() {
    $print_engine = $this->container->get('plugin.manager.entity_print.print_engine')->createInstance('testprintengine');
    $return = $this->container->get('entity_print.print_builder')->deliverPrintable([], $print_engine, TRUE);
    $this->assertFalse($return);
    // @TODO test that an exception have been logged? 
  }

1 Answer 1

2

There is no standard test feature to assert a logged message.

The simplest approach is to just install dblog in your test and then inspect the watchdog table for the expected record.

Alternatively, You could write your own log backend that stores it in memory and then access it from there if you don't want to install the necessary database tables in the test.

Or, don't use watchdog_exception() but an injected logger service that you can mock and then configure that to expect the call.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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