An overview of PHPUnit Automated testing in Drupal 8, including a comparison of manual testing vs automated testing, the pros and cons of automated testing, and the types of automated tests available in Drupal 8.
We all know that PHPunit testing framework has been added into Drupal 8. More than that SimpleTest in Drupal 8 is deprecated now. PHP unit testing also helps you to check you business logic So let's learn and discuss about, how to write the PHPUnit test for our requirement.
Test all the things! Automated testing with Drupal 8Sam Becker
With Drupal 8 released, one of the most important aspects of building a website or module has changed dramatically for the better. Developers now have a myriad of tools at their disposal to be able to test their code. If you are interested in improving your code and preventing bugs, but are unfamiliar with acronyms like BTB, KTB and WTB, this session is for you. If you’ve dabbled in testing but haven’t explored the depths of PHPUnit or Mink, then this session is for you.
Watch Erik's presentation on PHP Unit Testing to gain familiarity with unit tests and unit testing here at Tagged, with the testing framework currently in place and also learn how to write (better) unit tests. Download his slides here or email him at ejohannessen@tagged.com.
Key items of the presentation will be:
What is PHPUnit
Whats new in testing in Drupal 8
Core Classes and Components
Core/ Contibuted modules
PHPUnit file structure, namespace, and required metadata
Running PHPUnit tests.
Available tools for running automated tests.
Efficient JavaScript Unit Testing, May 2012Hazem Saleh
One of the biggest challenges of many web applications is the support on the different browsers with different versions. JavaScript code that runs on Safari does not necessarily mean it will work on IE or Firefox or Google chrome. This challenge is inherited from the lack of testing the JavaScript code that lives in the presentation tier from day one. Without unit testing the JavaScript code, organization will pay much money for testing, re-testing, and re-testing web applications for just deciding upgrading or supporting new browsers. This presentation shows the solution of this problem.
We all know that PHPunit testing framework has been added into Drupal 8. More than that SimpleTest in Drupal 8 is deprecated now. PHP unit testing also helps you to check you business logic So let's learn and discuss about, how to write the PHPUnit test for our requirement.
Test all the things! Automated testing with Drupal 8Sam Becker
With Drupal 8 released, one of the most important aspects of building a website or module has changed dramatically for the better. Developers now have a myriad of tools at their disposal to be able to test their code. If you are interested in improving your code and preventing bugs, but are unfamiliar with acronyms like BTB, KTB and WTB, this session is for you. If you’ve dabbled in testing but haven’t explored the depths of PHPUnit or Mink, then this session is for you.
Watch Erik's presentation on PHP Unit Testing to gain familiarity with unit tests and unit testing here at Tagged, with the testing framework currently in place and also learn how to write (better) unit tests. Download his slides here or email him at ejohannessen@tagged.com.
Key items of the presentation will be:
What is PHPUnit
Whats new in testing in Drupal 8
Core Classes and Components
Core/ Contibuted modules
PHPUnit file structure, namespace, and required metadata
Running PHPUnit tests.
Available tools for running automated tests.
Efficient JavaScript Unit Testing, May 2012Hazem Saleh
One of the biggest challenges of many web applications is the support on the different browsers with different versions. JavaScript code that runs on Safari does not necessarily mean it will work on IE or Firefox or Google chrome. This challenge is inherited from the lack of testing the JavaScript code that lives in the presentation tier from day one. Without unit testing the JavaScript code, organization will pay much money for testing, re-testing, and re-testing web applications for just deciding upgrading or supporting new browsers. This presentation shows the solution of this problem.
Most projects in CF now involve creating some type of consumable CFC Endpoint or API Service... do you Unit test your API, do you use Integration Tests on your API? How many ways do you test your API? Not all tests are created equal.
We build our CFCs and CF API to be consumed with CF Apps, Mobile Apps, Javascript apps and devices we haven’t even thought about yet. To be smart developers we need to be able to test our CFC endpoints, and the code that uses those endpoints.
We’ll learn how to test your API serverside with Testbox and Clientside with Jasmine.
With Testbox and Jasmine both using BDD, your test code can almost be isomorphic.
Attendees should have some exposure to CFCs as endpoints, or CF API creations, and consuming with other languages/devices, in this case, JavaScript.
Attendees will learn
How to use Testbox to test your CFCs 2 different ways
Different types and ways to test JavaScript
Overview of client/server side testing tools
Building testing into your workflow
You are one of many that are not testing your APIs thoroughly
This workshop is about testing the right way. Get a clear view on how to test your code in an efficient and useful way!
This first testing-related workshop is about all aspects of unit testing. Integration testing and TDD will have their own dedicated workshops.
Workshop: Functional testing made easy with PHPUnit & Selenium (phpCE Poland,...Ondřej Machulda
Annotated slides for phpCE workshop on November 3, 2017.
Workshop repository: https://github.com/OndraM/selenium-workshop-phpce
The workshop covered:
- setting up local development environment (using Docker)
- practical examples of functional tests implementation
- exploring possibilities of Selenium WebDriver
- parallel test execution using Steward
- hands-on Page Object design pattern
- dealing with asynchronous elements of web-pages (AJAX, JavaScript)
- general tips & tricks how to keep a maintainable suite of functional tests in a long-term
Mal ganz ehrlich: Testen im Frontend hat noch nie viel Spaß gemacht. In meinem Talk möchte ich mit Jest eine Testbibliothek vorstellen, die genau das ändern kann. Jest lässt sich ohne viel Konfiguration direkt einsetzen und bringt alles mit, was man von einer Testbibliothek erwartet (und noch mehr).
An vielen praktischen Beispielen möchte ich meine Lieblingsfeatures wie Snapshot-Tests, Mocking oder das tolle CLI erläutern und zeigen, dass Testen im Frontend durchaus Spaß machen kann. Eine Ausrede weniger, um auf das Testen im Frontend zu verzichten!
Vorkenntnisse:
Grundlegende JavaScript-Kenntnisse.
Lernziele:
Die Teilnehmer sollen einen Überblick über die Funktionsweise und die Einsatzbereiche von Jest bekommen. Sie lernen, wie sie für Tests in Frontend-Projekten mit Jest im Werkzeugkoffer gut gerüstet sind.
Most projects in CF now involve creating some type of consumable CFC Endpoint or API Service... do you Unit test your API, do you use Integration Tests on your API? How many ways do you test your API? Not all tests are created equal.
We build our CFCs and CF API to be consumed with CF Apps, Mobile Apps, Javascript apps and devices we haven’t even thought about yet. To be smart developers we need to be able to test our CFC endpoints, and the code that uses those endpoints.
We’ll learn how to test your API serverside with Testbox and Clientside with Jasmine.
With Testbox and Jasmine both using BDD, your test code can almost be isomorphic.
Attendees should have some exposure to CFCs as endpoints, or CF API creations, and consuming with other languages/devices, in this case, JavaScript.
Attendees will learn
How to use Testbox to test your CFCs 2 different ways
Different types and ways to test JavaScript
Overview of client/server side testing tools
Building testing into your workflow
You are one of many that are not testing your APIs thoroughly
This workshop is about testing the right way. Get a clear view on how to test your code in an efficient and useful way!
This first testing-related workshop is about all aspects of unit testing. Integration testing and TDD will have their own dedicated workshops.
Workshop: Functional testing made easy with PHPUnit & Selenium (phpCE Poland,...Ondřej Machulda
Annotated slides for phpCE workshop on November 3, 2017.
Workshop repository: https://github.com/OndraM/selenium-workshop-phpce
The workshop covered:
- setting up local development environment (using Docker)
- practical examples of functional tests implementation
- exploring possibilities of Selenium WebDriver
- parallel test execution using Steward
- hands-on Page Object design pattern
- dealing with asynchronous elements of web-pages (AJAX, JavaScript)
- general tips & tricks how to keep a maintainable suite of functional tests in a long-term
Mal ganz ehrlich: Testen im Frontend hat noch nie viel Spaß gemacht. In meinem Talk möchte ich mit Jest eine Testbibliothek vorstellen, die genau das ändern kann. Jest lässt sich ohne viel Konfiguration direkt einsetzen und bringt alles mit, was man von einer Testbibliothek erwartet (und noch mehr).
An vielen praktischen Beispielen möchte ich meine Lieblingsfeatures wie Snapshot-Tests, Mocking oder das tolle CLI erläutern und zeigen, dass Testen im Frontend durchaus Spaß machen kann. Eine Ausrede weniger, um auf das Testen im Frontend zu verzichten!
Vorkenntnisse:
Grundlegende JavaScript-Kenntnisse.
Lernziele:
Die Teilnehmer sollen einen Überblick über die Funktionsweise und die Einsatzbereiche von Jest bekommen. Sie lernen, wie sie für Tests in Frontend-Projekten mit Jest im Werkzeugkoffer gut gerüstet sind.
Principles and patterns for test driven developmentStephen Fuqua
Developed to help introduce key topics in Test Driven Development, for new and veteran developers alike. Some examples are language-specific (C# / MSTest / Moq), but the principles apply to any object oriented language.
Breaking Dependencies to Allow Unit TestingSteven Smith
Unit testing software can be difficult, especially when the software wasn't designed to be testable. Dependencies on infrastructure concerns and software we don't control are one of the biggest contributors to testing difficulty. In this session, you'll learn the difference between unit tests and other kinds of tests, how to recognize and invert dependencies, and how to unit test your code's interactions with these dependencies without testing the infrastructure itself.
Presented at FalafelCON 2014, San Francisco, September 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014FalafelSoftware
Unit testing software can be difficult, especially when the software wasn't designed to be testable. Dependencies on infrastructure concerns and software we don't control are one of the biggest contributors to testing difficulty. In this session, you'll learn the difference between unit tests and other kinds of tests, how to recognize and invert dependencies, and how to unit test your code's interactions with these dependencies without testing the infrastructure itself.
Breaking Dependencies to Allow Unit TestingSteven Smith
Unit testing software can be difficult, especially when the software wasn't designed to be testable. Dependencies on infrastructure concerns and software we don't control are one of the biggest contributors to testing difficulty. In this session, you'll learn the difference between unit tests and other kinds of tests, how to recognize and invert dependencies, and how to unit test your code's interactions with these dependencies without testing the infrastructure itself.
Infinum Android Talks #17 - Testing your Android applications by Ivan KustInfinum
van will show you how to setup unit tests using Robolectric, how to test user interactions using Espresso and provide some tips and tricks for stress-free testing.
The slides or my talk at SoftShake (soft-shake 2013) about unit test maintenance.
The code can be found here : https://github.com/tsimbalar/UnitTestsMaintenanceHell
Abstract (in French, sorry ...) :
“Oui, les tests unitaires, c’est cool, mais à chaque fois que je fais une petite modification dans le code, je dois réparer tous mes tests, c’est pénible et ça me prend un temps fou! Alors j’hésite à laisser tomber ma suite de tests, ou alors je fais l’impasse sur ce refactoring …”
Vous avez déjà entendu ça, non ? Quand on se met à écrire des tests unitaires (que ce soit avant ou après le code à tester), au début, c’est la galère, puis, peu à peu, avec l’habitude et l’expérience, on les écrit mieux et plus rapidement … mais quand il s’agit de modifier du code existant, on a quand même l’impression de se prendre les pieds dans les tests.
Dans cette session, je vous présenterai quelques techniques, trucs et outils pour écrire des tests plus maintenables et vous sentir moins gênés lors des refactorings du code. Cette présentation se basera sur des exemples de code et des démos (en C# et avec Visual Studio)
Les tests apportent une forte valeur ajoutée à nos projets, ce qu’il faut, c’est essayer d’en réduire le coût…
When assertthat(you).understandUnitTesting() failsMartin Skurla
When assertthat(you).understandUnitTesting() fails:
1.) Test face-lifting
2.) Handling assertions
3.) Declarative and Data driven testing
4.) Advanced techniques
5.) Results
Staying Sane with Drupal (A Develper's Survival Guide)Oscar Merida
Drupal is a powerful content management framework and among the most succesful PHP projects out there. Working with Drupal's modules and theme layer means that for any problem there's more than one way to that that. Picking a good solution, or dealing with the choices of previous developers will make you pull your hair out. I'll look at what you can do to make working with Drupal, shall we say, enjoyable? We'll look at how to evaluate contributed modules, what modules should be in all your installations, examine coding conventions in Drupal, and talk about development best practices for Drupal sites.
Similar to Automated php unit testing in drupal 8 (20)
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
2. • @jaypan on Drupal.org and drupal.stackexchange.com
• Acquia certified Drupal Grandmaster
• Acquia Certified Developer
• Acquia Certified Developer – Front end specialist
• Acquia Certified Developer – Back end specialist
• Living in Japan since 2000
• Working with Drupal since 2007
• Currently writing a book on coding in Drupal
JAY FRIENDLY
3. JAY FRIENDLY
• Owner of Jaypan in Yokohama
• English https://www.jaypan.com
• Japanese https://www.jaypan.jp
• Jaypan specializes in
• high-performance AJAX/JavaScript heavy applications
• Custom module/theme development
• App Development
• Drupal integration with outside technologies
• JavaScript libraries
• Linux programs
• Multiple Drupal instances
• Technical consulting and translation (Japanese/English)
4. OVERVIEW
• Manual testing vs. automated testing
• How do automated tests work?
• History of testing in Drupal
• Types of automated tests in Drupal
• Discussion of each type of test
5. MANUAL TESTING
• Developer creates new functionality
• Developer tests new functionality
• Other people (client, team-members) test new functionality
• Found bugs are fixed
6. PROBLEMS WITH MANUAL TESTING
• Complex functionality requires significant time to test
• Easy to forget to test a given scenario
• Changes to code require re-testing every scenario after any change
• Changes to code in other parts of the system may break functionality
without anyone realizing it
• As time passes, the conditions that need to be tested may be
forgotten or lost as project members change
• Coming back to code after a period of time means the developer is
not sure what is required
7. AUTOMATED TESTING
• Developer creates automated tests that run through all testing
scenarios
• Testing system runs all tests and reports any behaviors that are
unexpected (aka bugs)
8. BENEFITS OF AUTOMATED TESTING
• Removes requirement of getting humans to test after each code
change
• Tests are faster than human testing
• Tests for the whole system can be run before committing any code to
a production server, to ensure new functionality in one part of the
system hasn’t broken functionality in another part of the system.
• If (or rather, when) new bugs are found, tests can be added along
with the fix, to ensure that the bug never arises again
• Overall system is more stable.
9. PROBLEMS WITH AUTOMATED TESTING
• Writing tests takes a significant amount of time
• Extra time means extra development resources
• Clients cannot directly see tests, and may not understand the extra costs
in developing when there is nothing for them to look at.
• Tests only test what they have been written to test. If the developer does
not think to test something, a bug could exist. The existence of automated
tests in such a case may create a false sense of security
• Tests happen in a virtual (non-visible) environment, making them hard to
debug (and even create)
• Changing code often requires re-writing old tests
10. OR IN OTHER WORDS, WHAT IS IT?
HOW DOES A TEST WORK?
• A test will first run some code, then do ‘assertions’ to ensure that the results work as
expected.
• For example, in Drupal 8, nodes have a method id(), that returns the ID of the
node.
• An automated test would create a new node object, then run $node->id() and test:
• Was a result returned?
• Is the result an integer?
• Is the returned ID the expected (correct) ID of the node that was created?
• Any failed assertions result in a failed test, telling the developer exactly what failed,
so they know what to fix.
11. AUTOMATED TESTING IN DRUPAL - HISTORY
• Drupal 6 - Simpletest module
• Drupal 7 - Simpletest in core
• Drupal 8 -
• Simpletest still in core but deprecated (to be removed in D9)
• PHPUnit introduced into core
• This presentation focuses exclusively on PHPUnit
12. TYPES OF TESTS IN DRUPAL 8
• Unit tests
• Kernel tests
• Functional tests
• JavaScript functional tests
13. UNIT TESTS IN DRUPAL 8
• A Unit is a PHP Class (OOP)
• Unit tests test code, not user-end functionality
• Unit tests will test a single class, to ensure that it behaves as
expected
• Unit tests test the unit (class) alone in isolation, rather than in the
Drupal environment
• Unit testing is very fast, as the system does not need to be
bootstrapped to run the tests
14. UNIT TEST OVERVIEW
• Unit tests go in [MODULENAME]/tests/src/Unit
• Namespace is DrupalTests[MODULENAME]Unit
• Unit tests extend DrupalTestsUnitTestCase
• Annotation should include (at a minimum)
• Class:
• @coversDefaultClass - the class the the test is testing
• @group - the group of tests (usually module name) that the test belongs to
• Method:
• @covers - the method of the class being tested
15. UNIT TEST OVERVIEW
• Testing class name should end in ‘Test’
• Example: the test for the Person class would be PersonTest
• Testing method (function) name must start with ‘test’
• Example: the method used to test the id() method of Person
would be testId()
16. UNIT TEST OVERVIEW
• Test classes can have a setUp() method, that sets up
conditions/objects before each test in the test class.
• Useful when all tests require a similar set of conditions
• Test classes can also have a tearDown() method, where objects
are cleaned up after each test in the test class.
• Test classes can have a setUpBeforeClass() method that is run
once before the test class is run
• Test classes can have a tearDownAfterClass() method that is run
once after the test class is finished
17. CLASS (UNIT) TO BE TESTED
class Person {
private $id;
public function setId($id) {
$this->id = $id;
}
public function id() {
return $this->id();
}
}
18. EXAMPLE UNIT TEST FOR PERSON CLASS
/**
* @coversDefaultClass Person
*/
class PersonTest {
/**
* @covers ::setId()
*/
public testId() {
$person = new Person();
$person->setId(123);
$this->assertNotNull($person->getId(), ‘A value is returned for the ID’);
$this->assertTrue(is_int($person->id()), ‘The returned ID is an
integer’);
$this->assertEqual(123, $this->getId(), ‘The returned ID is correct’);
}
}
19. KERNEL TESTS
KERNEL TESTS IN DRUPAL 8
• Kernel tests are executed in a limited Drupal environment, similar to
the environment before Drupal has been installed
• Tests can access files and the database
• Declared modules are loaded, but not installed. Installation needs
to be done manually
• Kernel tests are slower than Unit tests, but faster than Functional
tests
20. KERNEL TEST OVERVIEW
• Kernel tests go in [MODULENAME]/tests/src/Kernel
• Namespace is DrupalTests[MODULENAME]Kernel
• Kernel tests extend DrupalTestsKernelTestBast
22. FUNCTIONAL TESTS IN DRUPAL 8
• Functional tests work in an installed Drupal environment
• Modules needed for the test need to be declared for installation
• Tests use an internal browser (aka code - not visual), where links
can be clicked, form elements can be filled out, and pages can be
requested, all programmatically
• Users, roles, blocks and other entities can be created
• Tests are slow as each test builds a new Drupal instance in which
to run the tests
23. FUNCTIONAL TEST OVERVIEW
• Unit tests go in [MODULENAME]/tests/src/Functional
• Namespace is DrupalTests[MODULENAME]Functional
• Unit tests extend DrupalTestsBrowserTestBase
• Annotation should include (at a minimum)
• Class:
• @group - the group of tests (usually module name) that the test belongs to
• $modules property contains an array of modules to be installed
• example: $modules = [‘node’, ‘restrict_ip’]
24. FROM RESTRICT IP MODULE
EXAMPLE FUNCTIONAL TEST
namespace DrupalTestsrestrict_ipFunctional;
/**
* @group restrict_ip
*/
class RestrictIpAccessTest extends RestrictIpBrowserTestBase // which extends BrowserTestBase
{
protected static $modules = ['restrict_ip', 'node'];
/**
* Test that a user is blocked when the module is enabled
*/
public function testModuleEnabled()
{
$adminUser = $this->drupalCreateUser(['administer restricted ip addresses', 'access administration
pages', 'administer modules']);
$this->drupalLogin($adminUser);
$this->drupalGet('admin/config/people/restrict_ip');
$this->assertStatusCodeEquals(200);
$this->checkCheckbox('#edit-enable');
$this->click('#edit-submit');
$this->assertSession()->pageTextContains('The page you are trying to access cannot be accessed from
your IP address.');
}
}
25. JAVASCRIPT FUNCTIONAL TESTS IN DRUPAL
8
• JavaScript Functional tests work in a fully installed Drupal
environment
• Extends Functional tests to include JavaScript
• Require PhantomJS browser
• Virtual browser (no GUI)
• Requires installation on testing computer/server
• Can test #ajax methods, as well as other JavaScript functionality
26. JAVASCRIPT FUNCTIONAL TEST OVERVIEW
• Unit tests go in [MODULENAME]/tests/src/FunctionalJavascript
• Namespace is
DrupalTests[MODULENAME]FunctionalJavascript
• Unit tests extend
DrupalFunctionalJavascriptTestsJavascriptTestBase
• Annotation should include (at a minimum)
• Class:
• @group - the group of tests (usually module name) that the test
belongs to
27. FROM FANCY LOGIN MODULE
EXAMPLE JAVASCRIPT FUNCTIONAL TEST
namespace DrupalTestsfancy_loginFunctionalJavascript;
/**
* @group fancy_login
*/
class FancyLoginJavascriptTest extends FancyLoginJavascriptTestBase // which extends JavascriptTestBase
{
public function testDimmerBackgroundColor()
{
$this->openPopup();
$this->assertJsCondition('jQuery("#fancy_login_dim_screen").not(":animated")');
$this->assertJsCondition('jQuery("#fancy-login-user-login-form").not(":animated")');
$script = $this->createScriptString('#fancy_login_dim_screen', 'background-color', 'rgb(255, 255,
255)');
if(!$this->getSession()->evaluateScript($script))
{
throw new Exception('background-color is not white');
}
// …
}
}
28. WRITE TESTS THEN CODE
TESTING DRIVEN DEVELOPMENT
• Write tests as the start of the project, rather than the end
• Developers build and test as they go
• Gives a clear indicator of what to do next
• Gives a clear indication of when the project is complete
• Note - testing driven development is purely theoretical for me - I’ve
never done it
29. WHERE TO GO FROM HERE
• PHPUnit in Drupal 8 - https://www.drupal.org/docs/8/phpunit
• Documentation is limited
• Lots and lots of Googling