Here are a few key points about using PHPUnit for Selenium testing:
- PHPUnit provides a SeleniumTestCase class that allows you to write Selenium tests that extend it. This gives you access to Selenium commands like open(), type(), click(), assertTitle(), etc.
- You'll need to have Selenium Server and a supported browser (Firefox, Chrome, IE) installed to run the tests.
- Tests using SeleniumTestCase are more like integration/acceptance tests that simulate user interactions and verify page content rather than isolated unit tests.
- Common things to test include page titles, form submissions, link navigation, page content validation after actions.
- Selenium IDE can be used to record tests that can be exported to PHPUnit
The presentation explains the PHP unit testing framework and provides a basic training on Testing with PHPunit. It Covers fundamental of unit testing, unit testing benefits and best practices. Starting ground up from PHP unit fundamentals, features of unit testing tries to explore advanced topics like Data providers, Fuxtures, Test doubles and more...
phpunit is testing framework for php testing.
A browser is able to give the syntax error but what if in case of some logical error.
Phpunit testing enables you to check your logic.
It is fully object oriented framework.
It also can be enabled in Netbeans.
you can find the option of phpunit testing in Netbeans
Developer testing 101: Become a Testing FanaticLB Denker
In this workshop we will cover the methodologies and three basic levels of testing, then we will deep dive into how to use PHPUnit to achieve developer testing. The tests may not be the prettiest, most robust, or efficient, but you should leave the course with the ability and confidence to write tests for your code.
Topics include: xUnit framework basics and workflows, test classification, asserts, data driven testing, and an introduction to mocking.
This is a beginner course, but seasoned veterans may discover features they never knew.
The presentation explains the PHP unit testing framework and provides a basic training on Testing with PHPunit. It Covers fundamental of unit testing, unit testing benefits and best practices. Starting ground up from PHP unit fundamentals, features of unit testing tries to explore advanced topics like Data providers, Fuxtures, Test doubles and more...
phpunit is testing framework for php testing.
A browser is able to give the syntax error but what if in case of some logical error.
Phpunit testing enables you to check your logic.
It is fully object oriented framework.
It also can be enabled in Netbeans.
you can find the option of phpunit testing in Netbeans
Developer testing 101: Become a Testing FanaticLB Denker
In this workshop we will cover the methodologies and three basic levels of testing, then we will deep dive into how to use PHPUnit to achieve developer testing. The tests may not be the prettiest, most robust, or efficient, but you should leave the course with the ability and confidence to write tests for your code.
Topics include: xUnit framework basics and workflows, test classification, asserts, data driven testing, and an introduction to mocking.
This is a beginner course, but seasoned veterans may discover features they never knew.
A couple of tricks you might not know about. Held at an internal developer show'n'tell in October 2010 at SilverStripe Ltd. in Wellington, New Zealand. Video available at http://vimeo.com/16446690
Unit testing, everyone talks about it and wants to do it but never gets around to actually start testing. Complex spaghetti code and time / budget pressures are often the reasons why nobody dives in and gets started with testing. But when the application breaks, and people loose money or worse it's often too late.
In this talk I will take you on a journey with real examples that will show you how you can set up your tests, how to test complex situations with legacy spaghetti code, test web services, database interactions and how to gradually build a solid foundation to safeguard the core code base and everything around it.
Don't you want to be confident when you walk out the office?
Outlines the refactoring effort of the SilverStripe CMS codebase, which was an internal project at SilverStripe Ltd. mid 2009. The main objective was to simplify CMS extensions for intermediate frontend/backend developers. In practice this meant a lot of housekeeping, and the consistent usage of jQuery and jQuery UI over PrototypeJS.
Unit testing with PHPUnit - there's life outside of TDDPaweł Michalik
Basics of PHPUnit and why is it even more relevant in legacy code. Key points of the framework are explained, along with mocking objects, test organisation, creating documentations with tests and accessing non-public objects (where applicable).
Live version with additional notes available at: http://pawelmichalik.net/presentations/unit-testing-with-phpunit?showNotes=true
Prezentacja dostępna także w języku polskim: http://pawelmichalik.net/prezentacje/testy-jednostkowe-w-phpunit?showNotes=true
Why Your Test Suite Sucks - PHPCon PL 2015CiaranMcNulty
Many teams adopt TDD attracted by the promise of a more productive workflow, fewer regressions and higher code quality. Sometimes this goes wrong and these benefits do not materialise, despite a healthy-seeming test suite. In this talk we will look at what the common pitfalls of testing are, why teams fall into these traps, and they can dig themselves out.
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...GeeksLab Odessa
5.12.15 QA Lab: тестирование программного обеспечения.
Upcoming events: goo.gl/I2gJ4H
Доклад о Play-Swagger, проекте с открытым исходным кодом, разрабатываемом в Zalando с использованием Scala и Play Framework. О том, как использование API First и Swagger позволяет ускорить процесс разработки, упростить взаимодействие команд и повысить качество продукта.
I present four design patterns that make your development easier and better. Design patterns are a fantastic way to make more readable code, as they make use of common ideas that many developers know and use. These patterns are tried and tested in the enterprise world.
The first one is dependency injection. This covers putting the variables that a class needs to function preferably inside a constructor.
The second one is the factory pattern. A factory moves the responsibility of instantiating an object to a third-party class.
The third one is dependency injection. This allows us to place a class' dependencies at one time, making it easy to come back and see what the class needs to survive.
Finally, we discuss the chain of responsibility. This allows complex operations to be handled by a chain of classes. Each class in the chain determines whether it is capable of handling the request and, if so, it returns the result.
PHP 7 was recently released, bringing some much-desired changes and improvements to the language. However, many developers haven't had the opportunity to use it for their projects and may not be familiar with the changes it brings. We'll remedy this by checking out the new "spaceship operator," demonstrating how static type hints produce clean code, and using anonymous classes to quickly implement interfaces on the fly. Attendees will also learn about breaking changes and "gotchas" to watch out for when making the upgrade and will receive pointers on getting started with PHP 7 today.
Thoughts and ideas on why and how to maintain a code repository with special attention to code style and documentation.
Includes some tips and recommendations about tools and standards you use or get inspiration from to keep your project in a good shape.
This presentation would help learn how to install, integrate, write automated test script with PHPUnit.Would also involve looking into different example and execute them.
A couple of tricks you might not know about. Held at an internal developer show'n'tell in October 2010 at SilverStripe Ltd. in Wellington, New Zealand. Video available at http://vimeo.com/16446690
Unit testing, everyone talks about it and wants to do it but never gets around to actually start testing. Complex spaghetti code and time / budget pressures are often the reasons why nobody dives in and gets started with testing. But when the application breaks, and people loose money or worse it's often too late.
In this talk I will take you on a journey with real examples that will show you how you can set up your tests, how to test complex situations with legacy spaghetti code, test web services, database interactions and how to gradually build a solid foundation to safeguard the core code base and everything around it.
Don't you want to be confident when you walk out the office?
Outlines the refactoring effort of the SilverStripe CMS codebase, which was an internal project at SilverStripe Ltd. mid 2009. The main objective was to simplify CMS extensions for intermediate frontend/backend developers. In practice this meant a lot of housekeeping, and the consistent usage of jQuery and jQuery UI over PrototypeJS.
Unit testing with PHPUnit - there's life outside of TDDPaweł Michalik
Basics of PHPUnit and why is it even more relevant in legacy code. Key points of the framework are explained, along with mocking objects, test organisation, creating documentations with tests and accessing non-public objects (where applicable).
Live version with additional notes available at: http://pawelmichalik.net/presentations/unit-testing-with-phpunit?showNotes=true
Prezentacja dostępna także w języku polskim: http://pawelmichalik.net/prezentacje/testy-jednostkowe-w-phpunit?showNotes=true
Why Your Test Suite Sucks - PHPCon PL 2015CiaranMcNulty
Many teams adopt TDD attracted by the promise of a more productive workflow, fewer regressions and higher code quality. Sometimes this goes wrong and these benefits do not materialise, despite a healthy-seeming test suite. In this talk we will look at what the common pitfalls of testing are, why teams fall into these traps, and they can dig themselves out.
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...GeeksLab Odessa
5.12.15 QA Lab: тестирование программного обеспечения.
Upcoming events: goo.gl/I2gJ4H
Доклад о Play-Swagger, проекте с открытым исходным кодом, разрабатываемом в Zalando с использованием Scala и Play Framework. О том, как использование API First и Swagger позволяет ускорить процесс разработки, упростить взаимодействие команд и повысить качество продукта.
I present four design patterns that make your development easier and better. Design patterns are a fantastic way to make more readable code, as they make use of common ideas that many developers know and use. These patterns are tried and tested in the enterprise world.
The first one is dependency injection. This covers putting the variables that a class needs to function preferably inside a constructor.
The second one is the factory pattern. A factory moves the responsibility of instantiating an object to a third-party class.
The third one is dependency injection. This allows us to place a class' dependencies at one time, making it easy to come back and see what the class needs to survive.
Finally, we discuss the chain of responsibility. This allows complex operations to be handled by a chain of classes. Each class in the chain determines whether it is capable of handling the request and, if so, it returns the result.
PHP 7 was recently released, bringing some much-desired changes and improvements to the language. However, many developers haven't had the opportunity to use it for their projects and may not be familiar with the changes it brings. We'll remedy this by checking out the new "spaceship operator," demonstrating how static type hints produce clean code, and using anonymous classes to quickly implement interfaces on the fly. Attendees will also learn about breaking changes and "gotchas" to watch out for when making the upgrade and will receive pointers on getting started with PHP 7 today.
Thoughts and ideas on why and how to maintain a code repository with special attention to code style and documentation.
Includes some tips and recommendations about tools and standards you use or get inspiration from to keep your project in a good shape.
This presentation would help learn how to install, integrate, write automated test script with PHPUnit.Would also involve looking into different example and execute them.
ABCs of Brand Advertising
This hands-on workshop will teach you how top brand advertisers use the web for marketing, what it takes to get their attention and how you can create innovative programs for brand advertisers.
Led by Shari Gunn, Vice President Advertising & Business Development, Kaboodle , Director, Marketing, Hearst Digital Media, VP, Marketing, Primedia’s Automotive Enthusiast Group
Chatham Economic Development Corporation 2015-2020 Strategic Action Agenda presentation, given at the April 2015 joint elected officials meeting at Central Carolina Community College.
To view the full strategic plan, visit www.chathamedc.org. Printed versions are available at the EDC office.
Viva La Revolution: Why Universal Banking is under siege and what needs to be...Aman Narain
The world is experiencing incredible change both politically and technologically where industries are being re-imagined almost daily. Universal Banking is one business model that has been a very profitable business model. However with the changes in customer needs, regulation, technology and the emergence of new competitors this industry is most vulnerable to disruption. Disruption not just from TechGiants like Google and Apple but more so more small starts and an ecosystem of new financial services providers who instead of a head on challenge may be thin slicing the industry into oblivion. All is not lost however there are actions Universal Banks can and must take and this presentation shares some thoughts around these.
Open Content in Kalimantan: Wikipedia and Open Street Map for Transparency Re...Wikimedia Indonesia
Making All Voices Count Open Content in Kalimantan: Wikipedia & Open Street Map for Transparency
http://www.makingallvoicescount.org/project/open-content-in-kalimantan-wikipedia-openstreetmap-for-transparency/
In 2010, I told everyone how to start unit testing Zend Framework applications. In 2011, let’s take this a step further by testing services, work flows and performance. Looking to raise the bar on quality? Let this talk be the push you need to improve your Zend Framework projects.
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)Jen Wong
FitNesse is a wiki-based software testing tool that can be a powerful addition to your Continuous Integration Environments. Its greatest advantages include providing visibility into tests and results, and providing access to test-writing by non-technical team members. We will:
* look at specific examples and code,
* discuss the advantages and drawbacks of using FitNesse as a test framework
* implement, deploy, and use a simple fixture in a fitnesse test
* review different kinds of fixtures, including decision table, script, query, html, and selenium webtest fixtures
* discuss some of the more interesting fixture extensions we've implemented, including JSON-based verification and the ability to pass in javascript code for dynamic verification
* use Hudson/Jenkins to run your FitNesse tests as a step in your Continuous Integration/Deployment process
A lot of people using PHPunit for testing their source code. While I was observing my team I recognized most of them are only using the standard assertions like 'assertEquals()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis and it digs deep into uncommon features of PHPUnit.
Leveling Up With Unit Testing - php[tek] 2023Mark Niebergall
Writing unit testing on a project can seem like a daunting task, and earning team and leadership buy-in can be challenging. Level up your skillset as we cover PHPUnit and Prophecy setup with composer, writing meaningful tests, restructuring existing classes with dependency injection to allow for unit testing, using mock objects, and releasing code confidently with test coverage. We will also discuss overcoming common biases, unit testing challenges, and shortcomings of unit testing.
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.
Starting unit testing on a project can seem like a daunting task, and earning team and leadership buy-in can be challenging. We'll walk-through setup with composer, creating the first test, restructuring existing classes with dependency injection to allow unit testing, and releasing code confidently with test coverage. We'll also discuss overcoming common biases, unit testing challenges, and shortcomings of unit testing.
Watch the presentation at https://www.youtube.com/watch?v=6v4_bEajDUk
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard assertions like 'assertEquals()' or 'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
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
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
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.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
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.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
2. Test Lint
• Test Lint
– Trustworthiness
– Maintainability
– Readability
• References
– Test Lint (http://docs.typemock.com/lint/ )
3. Trustworthy Tests
• Trustworthy Tests
– Always Asserts Something
– Avoid unpredictable factor
– Don’t depend on other tests
– Avoid Logic in Tests
4. Always Asserts Something
• Always Asserts Something
– Assertion means “Verification”
– Unit Tests need to “Check Something”
• Exceptions
– Check exception not thrown
• Name “Login_Call_NoExceptionThrown”
– Specified Mock Object
5. Avoid Unpredictable Factor
• Avoid Unpredictable Factor
– Unpredictable Factor
• Random Number
• Date Time
– Cause
• Unreliable/Inconsistent Result
• Hard to write Assertion statement
7. Don’t Depend on Other Tests
• Example
class LogAnalyzerDependTest extends PHPUnit_Framework_TestCase {
public function test_LogAnalyzerDepend_Construct_NoException() {
$this->analyzer = new LogAnalyzerDepend();
$this->analyzer->initialize();
}
public function test_IsValid_InValidContent_ReturnFalse() {
$this->test_LogAnalyzerDepend_Construct_NoException();
$this->assertFalse($this->analyzer->is_valid('abc'));
}
}
8. Don’t Depend on Other Tests
• Symptom
– A test calls another tests
– It requires other tests to create/delete objects
– A test depends on system state set by other tests
– Test order matters
9. Don’t Depend on Other Tests
• Why not?
– Cannot provide explicit testing result
– Implicit tests flow
– The testA failed because callee testB failed
• Solution
– Extract reused code to utility
– For create/delete object, use “setUp” and
“tearDown” instead
10. Avoid Logic in Tests
• Test more than one thing
– Number of Assertion > 1
– Logics better not in tests
• switch, if, or else statement
• foreach, for, or while loops
11. Avoid Logic in Tests- Example
• Test Code
public function test_ImplodeAndExplode_ValidContent_CorrectResult() {
$instance = new MoreThanOne();
$test_array = array('1', '2', '3');
$test_string = '1,2,3';
for ($i = 0; $i < 2; $i++) {
if ($i === 0) { // Test explode2
$result = $instance->explode2(',', $test_string);
$this->assertEquals($test_array, $result);
}
elseif ($i === 1) { // Test implode2
$result = $instance->implode2(',', $test_array);
$this->assertEquals($test_string, $result);
}
}
}
13. Trustworthiness – Do it
• Do it
– Testing only one thing
– Keep safe green zone
• No dependency to real database/network
• Keep result consistent
– Assuring code coverage
– Attitude
• Add a unit test for newly tickets/trackers
14. Maintainable Tests
• Maintainable Tests
– Test public function only
– Don’t Repeat Yourself
• Use Factory Function over Multiple Object Creation
• Use setUp
– Using setUp in a maintainable manner
– Avoid Over Specification in Tests
– Avoid multiple asserts
15. Test Public Function Only
• Test Public Function Only
– Design/Program by Contract
• Private/Protected method might be changed
– Extract private/protected function to new class
• Adopt Single Responsibility Principle (SRP)
16. Semantic Change
• Semantic Change is really a PAIN
– API change may break all tests
– Each test need to be changed
public function test_IsValid_InValidContent_ReturnFalse_New() {
$analyzer = new LogAnalyzer();
$analyzer->initialize(); // new requirement
$this->assertFalse($analyzer->is_valid('abc'));
}
17. Use Factory Function over Multiple
Object Creation
• Use a factory function
protected function create_LogAnalyzer() { // Factory Method
$analyzer = new LogAnalyzer();
$analyzer->initialize(); // New API handled here
return $analyzer;
}
public function test_IsValid_InValidContent_ReturnFalse() {
$analyzer = $this->create_LogAnalyzer(); // Use factory
$this->assertFalse($analyzer->is_valid('abc'));
}
18. Use setUp over Multiple Object
Creation
• Use setUp
protected function setUp() { // setUp method
$this->analyzer = new LogAnalyzer();
$this->analyzer->initialize(); // New API handled here
}
public function test_IsValid_InValidContent_ReturnFalse() {
$this->assertFalse($this->analyzer->is_valid('abc'));
}
public function test_IsValid_ValidContent_ReturnFalse() {
$this->assertTrue($this->analyzer->is_valid('valid'));
}
19. Maintainable setUp
• Maintainable setUp
– setUp() should be generic
• Cohesion
• Initialized object should be used in all tests
• Might not be appropriate to arrange mock/stub in
setUp()
– setUp() should be kept his readability
20. Avoid Over Specification in Test
• Over specified in test
– Verify internal state/behavior of object
– Using mocks when stubs are enough
– A test assumes specific order or exact string
matches when it isn’t required.
21. Verify internal state/behavior of object
• Solution
– Never verify internal state/behavior
– Maybe no need to test
public function
test_Initialize_WhenCalled_SetsDefaultDelimiterIsTabDelimiter(){
$analyzer = new LogAnalyzer();
$this->assertEquals(null,
$analyzer->GetInternalDefaultDelimiter()
);
$analyzer->Initialize();
$this->assertEquals('t',
$analyzer->GetInternalDefaultDelimiter()
);
}
22. Avoid Multiple Asserts
• Why not?
– Assertion failure will throw exception. Multiple
assertion cannot get all failure point at once
– Test multiple thing in one tests
• Solution
– Separate tests for different assertion
– Use data provider / parameter tests
23. Data Provider Sample
• Test Code
class DataTest extends PHPUnit_Framework_TestCase {
/**
* @dataProvider provider
*/
public function testAdd($a, $b, $c) {
$this->assertEquals($c, $a + $b);
}
public function provider() {
return array(
array(0, 0, 0),
array(0, 1, 1),
array(1, 0, 1),
array(1, 1, 3)
);
}
}
24. Readable Tests
• Test Naming
• Variable Naming
• Good Assert Message
• Separate Arrange and Assertion
• Mock and Stub Naming
25. Test Naming
• Function Name
– Test function name should be
test_<function>_<scenario>_<expect_behavior>
– Example
• test_escape_evenBackSlashesData_successEscape
26. Variable Name
• Avoid Hard Code in tests
public function test BadlyNamedTest() {
$log = new LogAnalyzer();
$result= log.GetLineCount("abc.txt");
$this->assertEquals(-100, result);
}
public function test WellNamedTest() {
$log = new LogAnalyzer();
$COULD_NOT_READ_FILE = -100;
$result= log.GetLineCount("abc.txt");
$this->assertEquals($COULD_NOT_READ_FILE, result);
}
27. Good Assertion Message
• Good Assertion Message
– Don’t repeat what the built-in test framework
outputs to the console.
– Don’t repeat what the test name explains.
– If you don’t have anything good to say, don’t say
anything.
– Write what should have happened or what failed
28. Separate Arrange and Assertion
• Separate Arrange and Assertion
public function test_BadAssertMessage() {
$this->assertEquals(COULD_NOT_READ_FILE,
log->GetLineCount("abc.txt")
);
}
public function test_GoodAssertMessage() {
$result = log->GetLineCount("abc.txt");
$this->assertEquals($COULD_NOT_READ_FILE, $result);
}
29. Mock and Stub Naming
• Include “mock” and “stub” in variable name
public function test_sendNotify_Mock_NoException() {
$notify_content = 'fake_content';
$mock_notifier = $this->getMock('NotifierInterface');
$mock_notifier->expects($this->once())
->method('notify')
->with($this->anything(),
$this->equalTo($notify_content));
$alert_system = new AlertSystem(
$mock_notifier,
$stub_provider
);
$alert_system->send_notify('Alert!!');
}
31. PHPUnit and Selenium
• Use PHPUnit to do
– Integration Test
– Acceptance Test
• References
– PHPUnit Selenium
• http://www.phpunit.de/manual/current/en/selenium.h
tml
• http://seleniumhq.org/documentation/
32. PHPUnit and Selenium
• Use PHPUnit and Selenium
class WebTest extends PHPUnit_Extensions_SeleniumTestCase {
protected function setUp() {
$this->setBrowser('*firefox');
$this->setBrowserUrl('http://www.example.com/');
}
public function testTitle() {
$this->open('http://www.example.com/');
$this->assertTitle('Example WWW Page');
}
}