0

I am writing my first test in Drupal 8's API and for some reason, I am unable to geocode.

When I run my code in a controller, it works fine, but when using a test, $addressCollection evaluates to false and I get the message 'The geocder returned FALSE'.

namespace Drupal\Tests\custom_tests\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Test that Geocoder works
 * Source: https://deninet.com/node/1631
 * 
 * Note: need to have Gecoder: Google Maps configured properly before testing.
 * 
 * @group custom_tests
 */
class GeocoderModuleTest extends BrowserTestBase {

  /**
   * The modules to load to run the test.
   *
   * @var array
   */
  public static $modules = [
    'geocoder',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    // $this->geocoder = \Drupal::service('geocoder');
    $this->geocoder = $this->container->get('geocoder');

    /* Values tested for */
    $this->staticAddress = 'St Patrick\'s Close, Wood Quay, Dublin 8, Ireland';
    $this->staticCordinates = [
      'longitude' => 53.339529,
      'latitude' => -6.271501,
    ];
  }

  /**
   * Tests the setting form.
   */
  public function testForm() {

    $plugins = array('googlemaps');
    $address = '1 Centennial Square, Victoria, BC V8W 1P6'; // Victoria City Hall

    // $this->geocoder = \Drupal::service('geocoder');
    $addressCollection = $this->geocoder->geocode($address, $plugins);

    if ($addressCollection) {
      $this->assertTrue(TRUE);
      // $coordinates = $addressCollection->first()->getCoordinates();

      // /* Check the longitudes */
      // $this->assertEquals(
      //   $staticCordinates['longitude'], 
      //   $coordinates->getLongitude(), 
      //   'The latitudes didn\'t match',
      //   0.001);

      // /* Check the latitudes */
      // $this->assertEquals(
      //   $staticCordinates['latitude'],
      //   $coordinates->getLatitude(),
      //   'The longitudes didn\'t match', 
      //   0.001);
    } else {
      $this->assertFalse(TRUE, 'The geocder returned FALSE');
    }
  }
}
2
  • Wouldn't think line cause a php error straight away: $this->staticAddress = 'St Patrick's Close, Wood Quay, Dublin 8, Ireland'; The apostrophe on Patrick's would interfer with your string declaration of that whole address. Or is that just the way its been pasted onto here?
    – Leigh
    Jun 4, 2019 at 14:15
  • @Leigh Sorry, yes. I entered an example Address. Editing... Jun 4, 2019 at 23:54

0

Your Answer

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

Browse other questions tagged or ask your own question.