SlideShare a Scribd company logo
New England Drupal Camp 2017
NO MORE EXCUSES
Test your modules!
Erich Beyrent
Erich Beyrent
Senior Drupal Developer at BioRAFT
Drupal:
https://www.drupal.org/u/ebeyrent
Twitter:
https://twitter.com/ebeyrent
LinkedIn:
https://www.linkedin.com/in/erichbeyrent
Agenda
❖ Why write automated tests?
Agenda
❖ Why write automated tests?
❖ Types of automated tests in Drupal 8
Agenda
❖ Why write automated tests?
❖ Types of automated tests in Drupal 8
❖ Unit Tests
❖ Kernel Tests
❖ Functional Tests
❖ Browser Tests
❖ Javascript Tests*
❖ Behavioral Tests*
Why write automated tests?
❖ Manual testing can be generally cheaper, especially for a
short-term project (i.e. one-time testing)
❖ Manual testing is BORING AF
❖ Manual testing is time-consuming for projects that
iterate
❖ Manual testing is hard to make exactly repeatable,
requires extensive documentation
Why write automated tests?
Why write automated tests?
❖ Better to discover bugs during local development and
build processes
❖ Gives developers the confidence to make changes
❖ Some tests are self-documenting*
Unit Tests
❖ Individual methods are tested as discrete units
❖ Unit tests are solitary
❖ Uses test doubles, or mocks to control behavior of
related components
❖ Unit tests are fast, no need to bootstrap Drupal
Unit Tests
❖ Unit tests go in my_module/tests/src/Unit
❖ Unit tests require a namespace in the form of
DrupalTestsmy_moduleUnit
❖ Unit tests should include the following annotations:
❖ Class:
❖ @coversDefaultClass - Specified the name of the class being tests
❖ @group - Specifies the group of tests, usually the name of your
module
❖ Method:
❖ @covers - Specifies the class method being tested
public function __construct() {
$this->httpClient = Drupal::service('httpd_client');
$this->logger = Drupal::logger('apod');
$this->config = Drupal::config('apod.api_config');
}
public function getAstronomyPictureOfTheDay() {
$uri = $this->addQueryString(
$this->url, ['query' => [
'api_key' => $this->config->get(‘api_key')
]]);
$response = $this->httpClient->request('GET', $uri);
return $this->handleResponse($response);
}
Unit Testing depends on
Dependency Injection.
/**
* ApodClient constructor.
*
* @param GuzzleHttpClientInterface $httpClient
* Instance of the Guzzle HTTP Client.
* @param DrupalCoreLoggerLoggerChannelFactoryInterface $logger
* Instance of the Logger factory.
* @param DrupalCoreConfigConfigFactoryInterface $config_factory
* Instance of an object that implements the ConfigFactoryInterface.
*/
public function __construct(
ClientInterface $httpClient,
LoggerChannelFactoryInterface $logger,
ConfigFactoryInterface $configFactory
) {
$this->httpClient = $httpClient;
$this->logger = $logger->get(‘apod');
$this->config = $configFactory->get(‘apod.api_config’);
}
Mocks Everywhere
❖ Drupal 8 supports many different ways to create mocks
❖ PHPUnit
❖ $mock = $this->getMockBuilder(MyClass::class)
->getMock()
❖ Prophesy
❖ $mock = $this->prophesize(MyClass::class)->reveal()
❖ Mockery
❖ $mock = Mockery::mock(MyClass::class)
Running PHPUnit
$ cd web
$ ../vendor/bin/phpunit -c ./core/phpunit.xml.dist 
--testsuite=unit --group=my_group
Demo
Kernel Tests
❖ Kernel tests are sociable
❖ Used when it’s not practical or easy to write mocks
❖ Kernel tests are executed in a minimal Drupal environment
❖ Tests have access to the database and files
❖ Tests must install dependent modules
❖ Kernel tests are slower than unit tests, because they need to
bootstrap Drupal.
Kernel Tests
❖ Kernel tests go in my_module/tests/src/Kernel
❖ Kernel tests require a namespace in the form of
DrupalTestsmy_moduleKernel
Kernel Tests
$ export SIMPLETEST_DB=‘mysql://user@localhost/testdb'
$ ../vendor/bin/phpunit -c ./core/phpunit.xml.dist 
--testsuite=kernel --group my_module
Demo
2 Unit Tests,
0 Integration Tests
http://searchsoftwarequality.techtarget.com/feature/FAQ-Automated-software-testing-basics
Automated Testing Pyramids
https://www.tomred.net/devops/different-levels-in-automated-testing.html
Automated Testing Pyramids
Functional Tests
❖ Also known as integration tests, or UI tests
❖ Integration tests balance out the expense of speed vs
confidence
❖ Integration tests are supported in Drupal 8 as Browser
tests and Javascript tests
Browser Tests
❖ Browser tests use a fully installed Drupal environment
❖ All required modules must be declared
❖ Tests use an internal web browser behind the scene
❖ Tests tend to run much slower than unit tests
❖ Javascript is not supported
Browser Tests
❖ Browser tests go in my_module/tests/src/Functional
❖ Browser tests require a namespace in the form of
DrupalTestsmy_moduleFunctional
❖ Unit tests should include the following annotations:
❖ Class:
❖ @group - Specifies the group of tests, usually the
name of your module
Browser Tests
$ cd web
$ ../vendor/bin/phpunit -c ./core/phpunit.xml.dist 
modules/custom/my_module/tests/src/Functional/MyTest.php
Demo
Javascript Tests
❖ Javascript tests go in my_module/tests/src/
FunctionalJavascript
❖ Browser tests require a namespace in the form of
DrupalTestsmy_moduleFunctionalJavascript
❖ Unit tests should include the following annotations:
❖ Class:
❖ @group - Specifies the group of tests, usually the
name of your module
Javascript Tests
❖ Tests require PhantomJS to run
❖ Uses a full Drupal installation
❖ Can be used to test AJAX functionality
❖ There is no UI
❖ Debugging occurs using a debugger
Javascript Tests
Install PhantomJS: http://phantomjs.org/download.html
Run PhantomJS:

$ phantomjs --ssl-protocol=any --ignore-ssl-errors=true --debug=true 
./vendor/jcalderonzumba/gastonjs/src/Client/main.js 
8510 1024 768
Run tests:

$ cd web
$ ../vendor/bin/phpunit -c ./core/phpunit.xml.dist 
modules/custom/apod/tests/src/FunctionalJavascript/
ApodBlockHtmlTest.php
Demo
Behavioral Tests
❖ Behat FTW!
❖ Gherkin is human readable, and self-documenting
❖ Behat runs in a full local browser (IE, Firefox, Chrome)
❖ Debugging is simple and easy
Behavioral Tests
"require-dev": {
"devinci/devinci-behat-extension": "^0.1.0",
"ingenerator/behat-tableassert": "^1.1.1"
}
Running Behat Tests
❖ behat.yml
$ ./vendor/bin/behat --tags non_core_modules
Demo
Tests Help Drive Development
❖ Before starting a feature, translate requirements to
Gherkin
❖ Before starting a class, stub out methods and associated
unit tests
❖ Add functionality and tests concurrently
❖ Before marking a project as done, make sure all tests
pass
Gotchas
❖ Unit tests may need rewrites after refactoring code
❖ Modules need to be enabled for tests (other than unit tests)
to run
❖ Schema can cause problems.
❖ $this->strictConfigSchema = FALSE;
❖ Traits can cause problems.
❖ $object->setStringTranslation($this-
>getStringTranslationStub())
❖ Debugging in PhantomJS isn’t fun.
Gotchas
❖ Permissions can cause problems (run tests as Apache
user)
❖ Traits can cause problems.
// Solution

$object->setStringTranslation($this->getStringTranslationStub());
Summary
❖ Unit tests are for testing class methods.
❖ Kernel tests are for testing APIs
❖ Functional and behavioral tests are for testing web
interfaces.
❖ Behat is amazing
Resources
❖ https://www.drupal.org/docs/8/phpunit
❖ https://www.drupal.org/docs/8/phpunit/phpunit-browser-test-
tutorial
❖ https://www.drupal.org/docs/8/phpunit/phpunit-javascript-testing-
tutorial
❖ https://blog.kentcdodds.com/write-tests-not-too-many-mostly-
integration-5e8c7fff591c
❖ http://james-willett.com/2016/10/finding-the-balance-between-unit-
functional-tests/
❖ https://www.lullabot.com/articles/an-overview-of-testing-in-drupal-8
Questions?
https://www.dokeos.com/wp-content/uploads/2014/06/29-questions-test-Dokeos-EN.jpg

More Related Content

What's hot

20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing
Vladimir Roudakov
 
Join the darkside: Selenium testing with Nightwatch.js
Join the darkside: Selenium testing with Nightwatch.jsJoin the darkside: Selenium testing with Nightwatch.js
Join the darkside: Selenium testing with Nightwatch.js
Seth McLaughlin
 
Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)
Deutsche Post
 
Testing nightwatch, by David Torroija
Testing nightwatch, by David TorroijaTesting nightwatch, by David Torroija
Testing nightwatch, by David Torroija
David Torroija
 
Writing Software not Code with Cucumber
Writing Software not Code with CucumberWriting Software not Code with Cucumber
Writing Software not Code with Cucumber
Ben Mabey
 
Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabs
Tudor Barbu
 
Code ceptioninstallation
Code ceptioninstallationCode ceptioninstallation
Code ceptioninstallation
Andrii Lagovskiy
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development tools
Simon Kim
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
Scott Becker
 
Testing Web Applications
Testing Web ApplicationsTesting Web Applications
Testing Web Applications
Seth McLaughlin
 
Automated interactive testing for i os
Automated interactive testing for i osAutomated interactive testing for i os
Automated interactive testing for i os
Mobile March
 
The Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsThe Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsJohn Anderson
 
Front-End Testing: Demystified
Front-End Testing: DemystifiedFront-End Testing: Demystified
Front-End Testing: Demystified
Seth McLaughlin
 
Lunch and learn: Cucumber and Capybara
Lunch and learn: Cucumber and CapybaraLunch and learn: Cucumber and Capybara
Lunch and learn: Cucumber and CapybaraMarc Seeger
 
Xdebug and Drupal8 tests (PhpUnit and Simpletest)
Xdebug and Drupal8 tests (PhpUnit and Simpletest)Xdebug and Drupal8 tests (PhpUnit and Simpletest)
Xdebug and Drupal8 tests (PhpUnit and Simpletest)
Francisco José Seva Mora
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
之宇 趙
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS偉格 高
 
You've done the Django Tutorial, what next?
You've done the Django Tutorial, what next?You've done the Django Tutorial, what next?
You've done the Django Tutorial, what next?
Andy McKay
 
The Gist of React Native
The Gist of React NativeThe Gist of React Native
The Gist of React Native
Darren Cruse
 
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Iakiv Kramarenko
 

What's hot (20)

20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing
 
Join the darkside: Selenium testing with Nightwatch.js
Join the darkside: Selenium testing with Nightwatch.jsJoin the darkside: Selenium testing with Nightwatch.js
Join the darkside: Selenium testing with Nightwatch.js
 
Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)
 
Testing nightwatch, by David Torroija
Testing nightwatch, by David TorroijaTesting nightwatch, by David Torroija
Testing nightwatch, by David Torroija
 
Writing Software not Code with Cucumber
Writing Software not Code with CucumberWriting Software not Code with Cucumber
Writing Software not Code with Cucumber
 
Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabs
 
Code ceptioninstallation
Code ceptioninstallationCode ceptioninstallation
Code ceptioninstallation
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development tools
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
 
Testing Web Applications
Testing Web ApplicationsTesting Web Applications
Testing Web Applications
 
Automated interactive testing for i os
Automated interactive testing for i osAutomated interactive testing for i os
Automated interactive testing for i os
 
The Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsThe Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web apps
 
Front-End Testing: Demystified
Front-End Testing: DemystifiedFront-End Testing: Demystified
Front-End Testing: Demystified
 
Lunch and learn: Cucumber and Capybara
Lunch and learn: Cucumber and CapybaraLunch and learn: Cucumber and Capybara
Lunch and learn: Cucumber and Capybara
 
Xdebug and Drupal8 tests (PhpUnit and Simpletest)
Xdebug and Drupal8 tests (PhpUnit and Simpletest)Xdebug and Drupal8 tests (PhpUnit and Simpletest)
Xdebug and Drupal8 tests (PhpUnit and Simpletest)
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
 
You've done the Django Tutorial, what next?
You've done the Django Tutorial, what next?You've done the Django Tutorial, what next?
You've done the Django Tutorial, what next?
 
The Gist of React Native
The Gist of React NativeThe Gist of React Native
The Gist of React Native
 
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
 

Similar to Test your modules

Aug penguin16
Aug penguin16Aug penguin16
Aug penguin16
alhino
 
Good practices for debugging Selenium and Appium tests
Good practices for debugging Selenium and Appium testsGood practices for debugging Selenium and Appium tests
Good practices for debugging Selenium and Appium tests
Abhijeet Vaikar
 
Mastering selenium for automated acceptance tests
Mastering selenium for automated acceptance testsMastering selenium for automated acceptance tests
Mastering selenium for automated acceptance testsNick Belhomme
 
Building JBoss AS 7 for Fedora
Building JBoss AS 7 for FedoraBuilding JBoss AS 7 for Fedora
Building JBoss AS 7 for Fedora
wolfc71
 
Browser-Based testing using Selenium
Browser-Based testing using SeleniumBrowser-Based testing using Selenium
Browser-Based testing using Seleniumret0
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022
Mark Niebergall
 
Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2
A.K.M. Ahsrafuzzaman
 
Dive into Play Framework
Dive into Play FrameworkDive into Play Framework
Dive into Play Framework
Maher Gamal
 
eXo Platform SEA - Play Framework Introduction
eXo Platform SEA - Play Framework IntroductioneXo Platform SEA - Play Framework Introduction
eXo Platform SEA - Play Framework Introductionvstorm83
 
Drupal 8 Every Day: An Intro to Developing With Drupal 8
Drupal 8 Every Day: An Intro to Developing With Drupal 8Drupal 8 Every Day: An Intro to Developing With Drupal 8
Drupal 8 Every Day: An Intro to Developing With Drupal 8
Acquia
 
Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and Maintenance
Jazkarta, Inc.
 
Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20
Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20
Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20
Michael Lihs
 
Behaviour Testing and Continuous Integration with Drupal
Behaviour Testing and Continuous Integration with DrupalBehaviour Testing and Continuous Integration with Drupal
Behaviour Testing and Continuous Integration with Drupalsmithmilner
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
LinkMe Srl
 
Bangpypers april-meetup-2012
Bangpypers april-meetup-2012Bangpypers april-meetup-2012
Bangpypers april-meetup-2012
Deepak Garg
 
Android UI Testing with Appium
Android UI Testing with AppiumAndroid UI Testing with Appium
Android UI Testing with Appium
Luke Maung
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
Yakov Fain
 
RichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesRichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile Devices
Pavol Pitoňák
 
Introduction to Play Framework
Introduction to Play FrameworkIntroduction to Play Framework
Introduction to Play Framework
Warren Zhou
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
Darren Craig
 

Similar to Test your modules (20)

Aug penguin16
Aug penguin16Aug penguin16
Aug penguin16
 
Good practices for debugging Selenium and Appium tests
Good practices for debugging Selenium and Appium testsGood practices for debugging Selenium and Appium tests
Good practices for debugging Selenium and Appium tests
 
Mastering selenium for automated acceptance tests
Mastering selenium for automated acceptance testsMastering selenium for automated acceptance tests
Mastering selenium for automated acceptance tests
 
Building JBoss AS 7 for Fedora
Building JBoss AS 7 for FedoraBuilding JBoss AS 7 for Fedora
Building JBoss AS 7 for Fedora
 
Browser-Based testing using Selenium
Browser-Based testing using SeleniumBrowser-Based testing using Selenium
Browser-Based testing using Selenium
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022
 
Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2
 
Dive into Play Framework
Dive into Play FrameworkDive into Play Framework
Dive into Play Framework
 
eXo Platform SEA - Play Framework Introduction
eXo Platform SEA - Play Framework IntroductioneXo Platform SEA - Play Framework Introduction
eXo Platform SEA - Play Framework Introduction
 
Drupal 8 Every Day: An Intro to Developing With Drupal 8
Drupal 8 Every Day: An Intro to Developing With Drupal 8Drupal 8 Every Day: An Intro to Developing With Drupal 8
Drupal 8 Every Day: An Intro to Developing With Drupal 8
 
Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and Maintenance
 
Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20
Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20
Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20
 
Behaviour Testing and Continuous Integration with Drupal
Behaviour Testing and Continuous Integration with DrupalBehaviour Testing and Continuous Integration with Drupal
Behaviour Testing and Continuous Integration with Drupal
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
 
Bangpypers april-meetup-2012
Bangpypers april-meetup-2012Bangpypers april-meetup-2012
Bangpypers april-meetup-2012
 
Android UI Testing with Appium
Android UI Testing with AppiumAndroid UI Testing with Appium
Android UI Testing with Appium
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
RichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesRichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile Devices
 
Introduction to Play Framework
Introduction to Play FrameworkIntroduction to Play Framework
Introduction to Play Framework
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
 

More from Erich Beyrent

{ JSON:API} 2 - A Path to Decoupled Drupal
{ JSON:API} 2 - A Path to Decoupled Drupal{ JSON:API} 2 - A Path to Decoupled Drupal
{ JSON:API} 2 - A Path to Decoupled Drupal
Erich Beyrent
 
Configuration as Dependency: Managing Drupal 8 Configuration with git and Com...
Configuration as Dependency: Managing Drupal 8 Configuration with git and Com...Configuration as Dependency: Managing Drupal 8 Configuration with git and Com...
Configuration as Dependency: Managing Drupal 8 Configuration with git and Com...
Erich Beyrent
 
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate ModuleDigital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Erich Beyrent
 
Hack-Proof Your Drupal App
Hack-Proof Your Drupal AppHack-Proof Your Drupal App
Hack-Proof Your Drupal AppErich Beyrent
 
Staging Drupal: Change Management Strategies for Drupal
Staging Drupal: Change Management Strategies for DrupalStaging Drupal: Change Management Strategies for Drupal
Staging Drupal: Change Management Strategies for Drupal
Erich Beyrent
 
Staging Drupal: Change Management Strategies for Drupal
Staging Drupal: Change Management Strategies for DrupalStaging Drupal: Change Management Strategies for Drupal
Staging Drupal: Change Management Strategies for Drupal
Erich Beyrent
 

More from Erich Beyrent (6)

{ JSON:API} 2 - A Path to Decoupled Drupal
{ JSON:API} 2 - A Path to Decoupled Drupal{ JSON:API} 2 - A Path to Decoupled Drupal
{ JSON:API} 2 - A Path to Decoupled Drupal
 
Configuration as Dependency: Managing Drupal 8 Configuration with git and Com...
Configuration as Dependency: Managing Drupal 8 Configuration with git and Com...Configuration as Dependency: Managing Drupal 8 Configuration with git and Com...
Configuration as Dependency: Managing Drupal 8 Configuration with git and Com...
 
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate ModuleDigital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module
 
Hack-Proof Your Drupal App
Hack-Proof Your Drupal AppHack-Proof Your Drupal App
Hack-Proof Your Drupal App
 
Staging Drupal: Change Management Strategies for Drupal
Staging Drupal: Change Management Strategies for DrupalStaging Drupal: Change Management Strategies for Drupal
Staging Drupal: Change Management Strategies for Drupal
 
Staging Drupal: Change Management Strategies for Drupal
Staging Drupal: Change Management Strategies for DrupalStaging Drupal: Change Management Strategies for Drupal
Staging Drupal: Change Management Strategies for Drupal
 

Recently uploaded

Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 

Recently uploaded (20)

Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 

Test your modules

  • 1. New England Drupal Camp 2017 NO MORE EXCUSES Test your modules! Erich Beyrent
  • 2. Erich Beyrent Senior Drupal Developer at BioRAFT Drupal: https://www.drupal.org/u/ebeyrent Twitter: https://twitter.com/ebeyrent LinkedIn: https://www.linkedin.com/in/erichbeyrent
  • 3.
  • 4. Agenda ❖ Why write automated tests?
  • 5. Agenda ❖ Why write automated tests? ❖ Types of automated tests in Drupal 8
  • 6. Agenda ❖ Why write automated tests? ❖ Types of automated tests in Drupal 8 ❖ Unit Tests ❖ Kernel Tests ❖ Functional Tests ❖ Browser Tests ❖ Javascript Tests* ❖ Behavioral Tests*
  • 7. Why write automated tests? ❖ Manual testing can be generally cheaper, especially for a short-term project (i.e. one-time testing) ❖ Manual testing is BORING AF ❖ Manual testing is time-consuming for projects that iterate ❖ Manual testing is hard to make exactly repeatable, requires extensive documentation
  • 9. Why write automated tests? ❖ Better to discover bugs during local development and build processes ❖ Gives developers the confidence to make changes ❖ Some tests are self-documenting*
  • 10. Unit Tests ❖ Individual methods are tested as discrete units ❖ Unit tests are solitary ❖ Uses test doubles, or mocks to control behavior of related components ❖ Unit tests are fast, no need to bootstrap Drupal
  • 11. Unit Tests ❖ Unit tests go in my_module/tests/src/Unit ❖ Unit tests require a namespace in the form of DrupalTestsmy_moduleUnit ❖ Unit tests should include the following annotations: ❖ Class: ❖ @coversDefaultClass - Specified the name of the class being tests ❖ @group - Specifies the group of tests, usually the name of your module ❖ Method: ❖ @covers - Specifies the class method being tested
  • 12. public function __construct() { $this->httpClient = Drupal::service('httpd_client'); $this->logger = Drupal::logger('apod'); $this->config = Drupal::config('apod.api_config'); } public function getAstronomyPictureOfTheDay() { $uri = $this->addQueryString( $this->url, ['query' => [ 'api_key' => $this->config->get(‘api_key') ]]); $response = $this->httpClient->request('GET', $uri); return $this->handleResponse($response); }
  • 13. Unit Testing depends on Dependency Injection.
  • 14. /** * ApodClient constructor. * * @param GuzzleHttpClientInterface $httpClient * Instance of the Guzzle HTTP Client. * @param DrupalCoreLoggerLoggerChannelFactoryInterface $logger * Instance of the Logger factory. * @param DrupalCoreConfigConfigFactoryInterface $config_factory * Instance of an object that implements the ConfigFactoryInterface. */ public function __construct( ClientInterface $httpClient, LoggerChannelFactoryInterface $logger, ConfigFactoryInterface $configFactory ) { $this->httpClient = $httpClient; $this->logger = $logger->get(‘apod'); $this->config = $configFactory->get(‘apod.api_config’); }
  • 15. Mocks Everywhere ❖ Drupal 8 supports many different ways to create mocks ❖ PHPUnit ❖ $mock = $this->getMockBuilder(MyClass::class) ->getMock() ❖ Prophesy ❖ $mock = $this->prophesize(MyClass::class)->reveal() ❖ Mockery ❖ $mock = Mockery::mock(MyClass::class)
  • 16. Running PHPUnit $ cd web $ ../vendor/bin/phpunit -c ./core/phpunit.xml.dist --testsuite=unit --group=my_group
  • 17. Demo
  • 18. Kernel Tests ❖ Kernel tests are sociable ❖ Used when it’s not practical or easy to write mocks ❖ Kernel tests are executed in a minimal Drupal environment ❖ Tests have access to the database and files ❖ Tests must install dependent modules ❖ Kernel tests are slower than unit tests, because they need to bootstrap Drupal.
  • 19. Kernel Tests ❖ Kernel tests go in my_module/tests/src/Kernel ❖ Kernel tests require a namespace in the form of DrupalTestsmy_moduleKernel
  • 20. Kernel Tests $ export SIMPLETEST_DB=‘mysql://user@localhost/testdb' $ ../vendor/bin/phpunit -c ./core/phpunit.xml.dist --testsuite=kernel --group my_module
  • 21. Demo
  • 22. 2 Unit Tests, 0 Integration Tests
  • 25. Functional Tests ❖ Also known as integration tests, or UI tests ❖ Integration tests balance out the expense of speed vs confidence ❖ Integration tests are supported in Drupal 8 as Browser tests and Javascript tests
  • 26. Browser Tests ❖ Browser tests use a fully installed Drupal environment ❖ All required modules must be declared ❖ Tests use an internal web browser behind the scene ❖ Tests tend to run much slower than unit tests ❖ Javascript is not supported
  • 27. Browser Tests ❖ Browser tests go in my_module/tests/src/Functional ❖ Browser tests require a namespace in the form of DrupalTestsmy_moduleFunctional ❖ Unit tests should include the following annotations: ❖ Class: ❖ @group - Specifies the group of tests, usually the name of your module
  • 28. Browser Tests $ cd web $ ../vendor/bin/phpunit -c ./core/phpunit.xml.dist modules/custom/my_module/tests/src/Functional/MyTest.php
  • 29. Demo
  • 30. Javascript Tests ❖ Javascript tests go in my_module/tests/src/ FunctionalJavascript ❖ Browser tests require a namespace in the form of DrupalTestsmy_moduleFunctionalJavascript ❖ Unit tests should include the following annotations: ❖ Class: ❖ @group - Specifies the group of tests, usually the name of your module
  • 31. Javascript Tests ❖ Tests require PhantomJS to run ❖ Uses a full Drupal installation ❖ Can be used to test AJAX functionality ❖ There is no UI ❖ Debugging occurs using a debugger
  • 32. Javascript Tests Install PhantomJS: http://phantomjs.org/download.html Run PhantomJS:
 $ phantomjs --ssl-protocol=any --ignore-ssl-errors=true --debug=true ./vendor/jcalderonzumba/gastonjs/src/Client/main.js 8510 1024 768 Run tests:
 $ cd web $ ../vendor/bin/phpunit -c ./core/phpunit.xml.dist modules/custom/apod/tests/src/FunctionalJavascript/ ApodBlockHtmlTest.php
  • 33. Demo
  • 34. Behavioral Tests ❖ Behat FTW! ❖ Gherkin is human readable, and self-documenting ❖ Behat runs in a full local browser (IE, Firefox, Chrome) ❖ Debugging is simple and easy
  • 35. Behavioral Tests "require-dev": { "devinci/devinci-behat-extension": "^0.1.0", "ingenerator/behat-tableassert": "^1.1.1" }
  • 36. Running Behat Tests ❖ behat.yml $ ./vendor/bin/behat --tags non_core_modules
  • 37. Demo
  • 38. Tests Help Drive Development ❖ Before starting a feature, translate requirements to Gherkin ❖ Before starting a class, stub out methods and associated unit tests ❖ Add functionality and tests concurrently ❖ Before marking a project as done, make sure all tests pass
  • 39. Gotchas ❖ Unit tests may need rewrites after refactoring code ❖ Modules need to be enabled for tests (other than unit tests) to run ❖ Schema can cause problems. ❖ $this->strictConfigSchema = FALSE; ❖ Traits can cause problems. ❖ $object->setStringTranslation($this- >getStringTranslationStub()) ❖ Debugging in PhantomJS isn’t fun.
  • 40. Gotchas ❖ Permissions can cause problems (run tests as Apache user) ❖ Traits can cause problems. // Solution $object->setStringTranslation($this->getStringTranslationStub());
  • 41. Summary ❖ Unit tests are for testing class methods. ❖ Kernel tests are for testing APIs ❖ Functional and behavioral tests are for testing web interfaces. ❖ Behat is amazing
  • 42. Resources ❖ https://www.drupal.org/docs/8/phpunit ❖ https://www.drupal.org/docs/8/phpunit/phpunit-browser-test- tutorial ❖ https://www.drupal.org/docs/8/phpunit/phpunit-javascript-testing- tutorial ❖ https://blog.kentcdodds.com/write-tests-not-too-many-mostly- integration-5e8c7fff591c ❖ http://james-willett.com/2016/10/finding-the-balance-between-unit- functional-tests/ ❖ https://www.lullabot.com/articles/an-overview-of-testing-in-drupal-8