Join us as we look at unit tests in Apex - what they are and where they fit within an efficient and effective testing strategy. We'll also consider the demands that implementing such a strategy makes on how Apex code is structured in a Force.com application. You'll leave with an appreciation of the test pyramid, and some specific examples of mocking techniques.
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
THE CHALLENGE:
Given you understand the value of test automation.
Given you are handed a legacy application to maintain and enhance
Given the application is in ASP.Net Web Forms
When you try to add tests
Then you find that test-driven development is literally impossible.
This document discusses integration testing of ColdBox applications using TestBox and MockBox. It defines integration testing as testing individual units combined as a group to expose faults in their interaction. The key benefits outlined are that integration tests allow testing of real use cases faster than end-to-end tests. The document recommends always integration testing as part of the development process and provides an overview of how to set up and run integration tests for a ColdBox application using TestBox.
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.
The document provides an overview of testing Apex code in Salesforce, including:
- Why unit testing is important for developing robust, error-free code that meets the minimum 75% test coverage requirement.
- How to write Apex test classes annotated with @isTest and define test methods using testMethod.
- Using Test.startTest() and Test.stopTest() to test governor limits.
- Examples of testing a trigger, visualforce controller, web services callouts, and external API callouts.
- Best practices for testing such as using System.assert(), achieving 100% coverage, and testing different user contexts with System.runAs().
Unit tests give developers and testers a quick way to look for logic errors in the methods of classes in Visual C#, Visual Basic, and Visual C++ projects. A unit test can be created one time and run every time that source code is changed to make sure that no bugs are introduced.
This document provides an overview of GoogleMock, a mocking framework for C++. It defines what a mock object is and why they are useful for testing. GoogleMock allows specifying expectations for mock method calls, including how many times a method will be called and what it will return. It provides matchers to check arguments and actions to define return values or behaviors. The document demonstrates how to write mock classes, set expectations, and use mocks in tests to verify code interactions and behavior.
Example First / A Sane Test-Driven Approach to ProgrammingJonathan Acker
We all know we need automated tests for our code - they are our guardian angel against regression bugs. But what exactly is the point in writing a test in advance - how does this even make sense? The first thing to grasp is that, at this stage, these are not tests - but specifications, which force us to think about exactly what we want to do - in advance. In addition TDD/BDD provide a rigorous methodology, which can help to keep us sane whilst developing complex code in steady confident steps.
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
THE CHALLENGE:
Given you understand the value of test automation.
Given you are handed a legacy application to maintain and enhance
Given the application is in ASP.Net Web Forms
When you try to add tests
Then you find that test-driven development is literally impossible.
This document discusses integration testing of ColdBox applications using TestBox and MockBox. It defines integration testing as testing individual units combined as a group to expose faults in their interaction. The key benefits outlined are that integration tests allow testing of real use cases faster than end-to-end tests. The document recommends always integration testing as part of the development process and provides an overview of how to set up and run integration tests for a ColdBox application using TestBox.
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.
The document provides an overview of testing Apex code in Salesforce, including:
- Why unit testing is important for developing robust, error-free code that meets the minimum 75% test coverage requirement.
- How to write Apex test classes annotated with @isTest and define test methods using testMethod.
- Using Test.startTest() and Test.stopTest() to test governor limits.
- Examples of testing a trigger, visualforce controller, web services callouts, and external API callouts.
- Best practices for testing such as using System.assert(), achieving 100% coverage, and testing different user contexts with System.runAs().
Unit tests give developers and testers a quick way to look for logic errors in the methods of classes in Visual C#, Visual Basic, and Visual C++ projects. A unit test can be created one time and run every time that source code is changed to make sure that no bugs are introduced.
This document provides an overview of GoogleMock, a mocking framework for C++. It defines what a mock object is and why they are useful for testing. GoogleMock allows specifying expectations for mock method calls, including how many times a method will be called and what it will return. It provides matchers to check arguments and actions to define return values or behaviors. The document demonstrates how to write mock classes, set expectations, and use mocks in tests to verify code interactions and behavior.
Example First / A Sane Test-Driven Approach to ProgrammingJonathan Acker
We all know we need automated tests for our code - they are our guardian angel against regression bugs. But what exactly is the point in writing a test in advance - how does this even make sense? The first thing to grasp is that, at this stage, these are not tests - but specifications, which force us to think about exactly what we want to do - in advance. In addition TDD/BDD provide a rigorous methodology, which can help to keep us sane whilst developing complex code in steady confident steps.
The document provides an overview of Quick Test Professional (QTP), a test automation tool. It discusses key aspects of QTP including recording and running tests, using object repositories, checkpoints, parameters, actions, recovery scenarios, and programmatic descriptions.
Rails makes it easy to write your tests with Minitest (A default testing framework used by rails).
This slide contains contents about:
1. WHY IS UNIT TEST NECESSARY / SO IMPORTANT?
- Unit Test make it easy to learn Rails Way.
2. THINGS YOU SHOULD KNOW
- You need to have database for test environment.
3. DIRECTORIES FOR TEST IN RAILS
4. WHAT IS FIXTURES?
5. MODEL TEST IN ACTION
- test_helper.rb
- Youre Test Case < ActiveSupport::TestCase < Minitest::Test
- A simple approach for TDD (Test Driven Development)
6. AVAILABLE ASSERTIONS
레일스는 Minitest 를 기본 테스팅 프레임워크로 포함하고 있습니다.
이 슬라이드에서는 미니테스트와 관련된 레일스 단위 테스트 관련 기본 개념에 대해서 설명합니다.
또한, 간단한 모델 테스트 케이스를 이용하여 실제 테스트를 수행하는 방법에 대해서 간략히 설명합니다.
What is UFT? HP's unified functional testing.Confiz
Unified Functional Testing (UFT) is HP's main automated functional testing tool that allows users to integrate QuickTest Pro with Service Test. UFT enables automated functional testing of applications. It provides various panes like the Solution Explorer, Toolbox, Canvas, and Output panes to design and run tests. Users can create simple tests with activities like Replace String and Concatenate String, connect the test steps, and map data from multiple sources to test functionality.
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
As an Apex developer, you can harness testing as a way of improving software quality. Every piece of code you write needs coverage in order to push it into production. Join us as we cover the ways you can set up your org for successful and painless test development. You'll learn common testing patterns, how to use test data factories and mocks, and learn best practices for various types of tests, including callout integration.
Leveraging Existing Tests in Automated Test Generation for Web ApplicationsSALT Lab @ UBC
This document describes a technique called Testilizer that combines manual and automated testing of web applications. Testilizer leverages existing manual test cases to generate new test cases by exploring the extended state flow graph in a way that stays close to the original manual test paths. It also regenerates assertions for the new test cases by reusing, exactly matching, or generating similar assertions to those in the original test cases. An evaluation of Testilizer showed it was able to generate test cases that improved code coverage while making significant use of input data, sequences, and assertions from the original manual test cases.
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
Test-driven development (TDD) involves writing unit tests before writing application code. TDD promotes writing high-quality code and prevents regressions. It follows a "red-green-refactor" process of writing a failing test, making it pass by writing minimal code, and refactoring the code. Unit test frameworks allow automating tests and isolating code dependencies using techniques like stubs, fakes, and mocks. Tests should be organized into test classes and follow a lifecycle of setup, execution, and teardown.
The document discusses automation testing concepts and how QuickTest Professional (QTP) can be used for test automation. It covers topics like what is test automation, benefits of automation, automation life cycle, when automation is applicable, introduction to QTP, testing process with QTP including creating, running and analyzing tests, record and run modes, options, working with test objects, managing test objects, main phases of testing with QTP, and types of checkpoints.
The document provides best practices for writing unit tests, including mocking external services, writing focused tests for individual code units, avoiding unnecessary assertions, using annotations to test exceptions, and refactoring code if tests become too complex. Good practices like giving tests descriptive names and adding new tests for each found bug are also recommended. The document emphasizes that tests should serve as documentation and prevent regressions.
The document provides an overview of Quick Test Professional (QTP), a test automation tool. It describes key aspects of QTP including the testing process, add-ins, recording and running tests, the object repository, object spy, object recognition, synchronization, checkpoints, parameters, actions, recovery scenarios, and programmatic object identification without using the object repository.
ALM Phase 2 - Test Configurations, Matrix, Libraries TrainingChris Williams
This document provides an overview and instructions for using various features in ALM including traceability matrices, test configurations, libraries and baselines. It discusses how to set up and generate traceability matrices, define test configurations and add data/coverage to them. It also explains what libraries and baselines are, how to create them, compare baselines and set up asset sharing between projects using baselines. The document is intended as training material for the ALM Phase 2 product and includes an agenda, step-by-step instructions and screenshots to illustrate the different features.
Automation testing involves recording user actions on an application and verifying its behavior. Quick Test Professional (QTP) is an automation testing tool that follows a 7 step process: 1) preparing the test environment; 2) recording user actions; 3) enhancing the test with checkpoints and parameters; 4) debugging the test; 5) running the test; 6) analyzing results; and 7) reporting defects. QTP allows dividing tests into logical units called actions to make tests more modular and reusable across multiple tests.
The document discusses unit testing, test-driven development (TDD), and acceptance test-driven development (ATDD). It begins with an introduction to the speaker and describes the importance and benefits of learning TDD. Various types of tests are defined, including unit tests, integration tests, and user interface tests. The basics of unit testing, including test structure and using doubles, are explained. TDD and how it works in an iterative cycle of writing a failing test, code, and refactoring is covered. ATDD is introduced as a way to write the right code through specification by examples and acceptance tests. The benefits of ATDD for different roles are outlined.
Quick Test Professional (QTP) is automation testing tool that allows testing of applications by automating common tasks like recording, playback, and validating results. The QTP testing process involves 7 main phases including preparing the test environment, recording tests, enhancing tests with parameters and checkpoints, running tests, and analyzing results. QTP uses objects, actions, checkpoints and other features to model tests at different levels of the application under test. Test results can be stored and reported using features like the object repository, test reports and integration with other tools.
SVR Technologies providing the course content of QTP. It was given by our experts to improve the knowledge of the readers which helps you in interview. For more details about other IT courses please visit http://www.svrtechnologies.com/
This is a slide set with some information about programmer testing. It includes test doubles, mockit and junit.
Visit http://jpereira.eu/2011/12/03/programming-testing/ for more information. If you want to download these slides, please contact me (find my contacts on my blog)
Unit testing tests individual units of source code to determine if they are fit for use. It is different from integration testing, which combines modules, and validation testing, which checks that a system meets specifications. The goal of unit testing is to isolate and test each part of a program to show that individual parts are correct. Unit testing provides benefits such as finding problems early, facilitating automated testing and change, and improving software quality. Guidelines for effective unit testing include knowing the objective of each test, making tests self-sufficient, ensuring tests are deterministic, following naming conventions, duplicating code for readability, testing results not implementation, and using isolation frameworks.
QA Fest 2019. Анна Чернышова. Self-healing test automation 2.0. The FutureQAFest
Мы уже разговаривали о self-healing автоматизации, как она работает, какие есть подходы, чем они хороши, плохи и о новом инструменте, который мы разрабатываем в EPAM. Наш продукт завершает стадию POC и настало время поделиться результатами и понять, насколько self-healing автоматизация поможет вашим тестам стать стабильнее? Или наоборот, навредит?... Приходи и узнаешь!
Unit testing in Apex has several benefits:
1. It forces developers to define requirements, which testing then validates.
2. Unit tests provide free regression testing and target compatibility testing.
3. Well-written unit tests can achieve code coverage requirements with less effort.
The document provides an overview of Quick Test Professional (QTP), a test automation tool. It discusses key aspects of QTP including recording and running tests, using object repositories, checkpoints, parameters, actions, recovery scenarios, and programmatic descriptions.
Rails makes it easy to write your tests with Minitest (A default testing framework used by rails).
This slide contains contents about:
1. WHY IS UNIT TEST NECESSARY / SO IMPORTANT?
- Unit Test make it easy to learn Rails Way.
2. THINGS YOU SHOULD KNOW
- You need to have database for test environment.
3. DIRECTORIES FOR TEST IN RAILS
4. WHAT IS FIXTURES?
5. MODEL TEST IN ACTION
- test_helper.rb
- Youre Test Case < ActiveSupport::TestCase < Minitest::Test
- A simple approach for TDD (Test Driven Development)
6. AVAILABLE ASSERTIONS
레일스는 Minitest 를 기본 테스팅 프레임워크로 포함하고 있습니다.
이 슬라이드에서는 미니테스트와 관련된 레일스 단위 테스트 관련 기본 개념에 대해서 설명합니다.
또한, 간단한 모델 테스트 케이스를 이용하여 실제 테스트를 수행하는 방법에 대해서 간략히 설명합니다.
What is UFT? HP's unified functional testing.Confiz
Unified Functional Testing (UFT) is HP's main automated functional testing tool that allows users to integrate QuickTest Pro with Service Test. UFT enables automated functional testing of applications. It provides various panes like the Solution Explorer, Toolbox, Canvas, and Output panes to design and run tests. Users can create simple tests with activities like Replace String and Concatenate String, connect the test steps, and map data from multiple sources to test functionality.
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
As an Apex developer, you can harness testing as a way of improving software quality. Every piece of code you write needs coverage in order to push it into production. Join us as we cover the ways you can set up your org for successful and painless test development. You'll learn common testing patterns, how to use test data factories and mocks, and learn best practices for various types of tests, including callout integration.
Leveraging Existing Tests in Automated Test Generation for Web ApplicationsSALT Lab @ UBC
This document describes a technique called Testilizer that combines manual and automated testing of web applications. Testilizer leverages existing manual test cases to generate new test cases by exploring the extended state flow graph in a way that stays close to the original manual test paths. It also regenerates assertions for the new test cases by reusing, exactly matching, or generating similar assertions to those in the original test cases. An evaluation of Testilizer showed it was able to generate test cases that improved code coverage while making significant use of input data, sequences, and assertions from the original manual test cases.
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
Test-driven development (TDD) involves writing unit tests before writing application code. TDD promotes writing high-quality code and prevents regressions. It follows a "red-green-refactor" process of writing a failing test, making it pass by writing minimal code, and refactoring the code. Unit test frameworks allow automating tests and isolating code dependencies using techniques like stubs, fakes, and mocks. Tests should be organized into test classes and follow a lifecycle of setup, execution, and teardown.
The document discusses automation testing concepts and how QuickTest Professional (QTP) can be used for test automation. It covers topics like what is test automation, benefits of automation, automation life cycle, when automation is applicable, introduction to QTP, testing process with QTP including creating, running and analyzing tests, record and run modes, options, working with test objects, managing test objects, main phases of testing with QTP, and types of checkpoints.
The document provides best practices for writing unit tests, including mocking external services, writing focused tests for individual code units, avoiding unnecessary assertions, using annotations to test exceptions, and refactoring code if tests become too complex. Good practices like giving tests descriptive names and adding new tests for each found bug are also recommended. The document emphasizes that tests should serve as documentation and prevent regressions.
The document provides an overview of Quick Test Professional (QTP), a test automation tool. It describes key aspects of QTP including the testing process, add-ins, recording and running tests, the object repository, object spy, object recognition, synchronization, checkpoints, parameters, actions, recovery scenarios, and programmatic object identification without using the object repository.
ALM Phase 2 - Test Configurations, Matrix, Libraries TrainingChris Williams
This document provides an overview and instructions for using various features in ALM including traceability matrices, test configurations, libraries and baselines. It discusses how to set up and generate traceability matrices, define test configurations and add data/coverage to them. It also explains what libraries and baselines are, how to create them, compare baselines and set up asset sharing between projects using baselines. The document is intended as training material for the ALM Phase 2 product and includes an agenda, step-by-step instructions and screenshots to illustrate the different features.
Automation testing involves recording user actions on an application and verifying its behavior. Quick Test Professional (QTP) is an automation testing tool that follows a 7 step process: 1) preparing the test environment; 2) recording user actions; 3) enhancing the test with checkpoints and parameters; 4) debugging the test; 5) running the test; 6) analyzing results; and 7) reporting defects. QTP allows dividing tests into logical units called actions to make tests more modular and reusable across multiple tests.
The document discusses unit testing, test-driven development (TDD), and acceptance test-driven development (ATDD). It begins with an introduction to the speaker and describes the importance and benefits of learning TDD. Various types of tests are defined, including unit tests, integration tests, and user interface tests. The basics of unit testing, including test structure and using doubles, are explained. TDD and how it works in an iterative cycle of writing a failing test, code, and refactoring is covered. ATDD is introduced as a way to write the right code through specification by examples and acceptance tests. The benefits of ATDD for different roles are outlined.
Quick Test Professional (QTP) is automation testing tool that allows testing of applications by automating common tasks like recording, playback, and validating results. The QTP testing process involves 7 main phases including preparing the test environment, recording tests, enhancing tests with parameters and checkpoints, running tests, and analyzing results. QTP uses objects, actions, checkpoints and other features to model tests at different levels of the application under test. Test results can be stored and reported using features like the object repository, test reports and integration with other tools.
SVR Technologies providing the course content of QTP. It was given by our experts to improve the knowledge of the readers which helps you in interview. For more details about other IT courses please visit http://www.svrtechnologies.com/
This is a slide set with some information about programmer testing. It includes test doubles, mockit and junit.
Visit http://jpereira.eu/2011/12/03/programming-testing/ for more information. If you want to download these slides, please contact me (find my contacts on my blog)
Unit testing tests individual units of source code to determine if they are fit for use. It is different from integration testing, which combines modules, and validation testing, which checks that a system meets specifications. The goal of unit testing is to isolate and test each part of a program to show that individual parts are correct. Unit testing provides benefits such as finding problems early, facilitating automated testing and change, and improving software quality. Guidelines for effective unit testing include knowing the objective of each test, making tests self-sufficient, ensuring tests are deterministic, following naming conventions, duplicating code for readability, testing results not implementation, and using isolation frameworks.
QA Fest 2019. Анна Чернышова. Self-healing test automation 2.0. The FutureQAFest
Мы уже разговаривали о self-healing автоматизации, как она работает, какие есть подходы, чем они хороши, плохи и о новом инструменте, который мы разрабатываем в EPAM. Наш продукт завершает стадию POC и настало время поделиться результатами и понять, насколько self-healing автоматизация поможет вашим тестам стать стабильнее? Или наоборот, навредит?... Приходи и узнаешь!
Unit testing in Apex has several benefits:
1. It forces developers to define requirements, which testing then validates.
2. Unit tests provide free regression testing and target compatibility testing.
3. Well-written unit tests can achieve code coverage requirements with less effort.
The document discusses various software testing strategies and techniques. It begins by explaining the importance of testing software before customers use it in order to reduce errors. It then describes different testing techniques including white-box testing, which tests the internal logic and paths of a program, and black-box testing, which tests the inputs and outputs against requirements without considering internal logic. The document provides examples of specific strategies like branch coverage, basis path testing, and boundary value analysis. It also discusses test case documentation and different testing phases from unit to integration to system testing.
John Kent - An Entity Model for Software TestingTEST Huddle
EuroSTAR Software Testing Conference 2008 presentation on An Entity Model for Software Testing by John Kent. See more at conferences.eurostarsoftwaretesting.com/past-presentations/
This document provides an overview of working with legacy code. It begins by defining legacy code as code without tests. It emphasizes the importance of writing tests before modifying legacy code to avoid introducing new bugs. The document outlines a process for working with legacy code that involves identifying requirements, understanding the code, writing tests, and then modifying the code. It discusses common obstacles like not understanding the code or not having time. It provides techniques for overcoming these obstacles, such as extracting methods, exposing static methods, and using test doubles. The document stresses having an attitude of cleaning up code and leaving it in a better state.
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.
Beginners overview of automated testing with Rspecjeffrey1ross
The document provides an overview of automated testing for beginning developers, covering testing basics like unit tests and code coverage, popular Ruby testing tools and techniques like RSpec and Capybara, the benefits of automated testing like improved code quality and efficiency, and strategies for testing models, controllers, and views. It also discusses testing patterns and principles like the inverted testing pyramid, page object pattern, and single responsibility principle.
This document discusses agile testing and how it differs from traditional testing approaches. It provides examples of how testing is conducted at different levels and phases in traditional versus agile approaches. The document emphasizes that agile and traditional testing are not the same, and that in agile, testing activities are incremental, iterative, and involve the whole team working together. It also provides background on the author and their expertise in agile testing and transformation.
Episode 5 - Writing unit tests in SalesforceJitendra Zaa
The document provides an agenda for a session on writing unit tests in Apex. It discusses why unit tests are important in Apex, how to structure test classes, best practices for testing, and resources for learning more about Apex testing. The session demonstrates executing unit tests and techniques like accessing private members, running tests within limits, and creating test data. Attendees are encouraged to ask questions during the last 15 minutes.
What is testing?
“An empirical, technical investigation conducted to provide stakeholders with information about the quality of the product under test.”
- Cem Kaner
Database Unit Testing Made Easy with VSTSSanil Mhatre
This document discusses database unit testing using Visual Studio Team System (VSTS). It begins with an overview of software testing basics and unit testing principles. It then covers database unit testing terminology, principles of isolation and independence, and testable interfaces of stored procedures. The document outlines different levels of unit testing and factors to consider. It demonstrates implementing database unit testing in VSTS 2010 and new features in VSTS 2012. The goal is to show how VSTS can be used to test database code and improve quality.
This document discusses different types of software testing including unit testing and integration testing. Unit testing involves writing code to test individual units or modules in isolation with few dependencies. Integration testing evaluates how modules function together as a group in a black box manner. The benefits of testing include facilitating code changes, enhancing software quality by catching bugs, serving as documentation, and improving code quality. Test-driven development is introduced as an approach where tests are written before code to drive the design. Continuous integration is also discussed as a way to fully automate testing, build, and code quality checks.
Agile Software Testing the Agilogy WayJordi Pradel
At Agilogy we have a curated way of testing software. In these slides we share basic Principles, Patterns and Strategies to test software in Hexagonal Architectures.
Defying the typical test pyramid, we focus our testing strategy on testing the whole domain. To do so, we avoid the abuse of mocks and stubs and, instead, we use hand-crafted test fakes that behave like their production counterparts. We make sure they actually do so by testing both the production driven adapters and their fakes with the very same test suite.
This document provides an introduction to unit testing using the NUnit framework. It defines unit testing as developer tests that validate code works as expected. Unit tests are part of the construction cycle and sit between technical design and QA testing in the software development lifecycle. Benefits of unit testing include early defect detection, better code design, regression protection, and learning new APIs. The document then describes NUnit attributes that mark test fixtures and methods. It also covers NUnit assertions for verification. Examples are provided of test-driven development and using NUnit for continuous integration.
Static testing examines and reviews software without executing it, while dynamic testing executes the software. There are different types of testing like unit, integration, system, and acceptance testing. Testing techniques include white box, black box, incremental, and thread testing. White box testing examines internal program structure and logic, while black box testing verifies requirements without considering internal structure.
Slides from Software Testing Techniques course offered at Kansas State University in Spring'16 and Spring'17. Entire course material can be found at https://github.com/rvprasad/software-testing-course.
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.
This document discusses test automation and provides an overview of various topics related to automated testing including:
1. The presenter provides an introduction and agenda which includes discussing the testing pyramid, automated vs manual testing, return on investment for test automation, and popular test automation tools.
2. Popular automation tools that are discussed include HP UFT, TestComplete, Selenium, and Cucumber. Methodologies like keyword driven testing and data driven testing are also covered.
3. Setting up an automation testing framework is also addressed, and behavior driven development with tools like Cucumber and Thucydides is explained.
4. To conclude, the presenter provides additional resources for learning more about test automation and gives examples
Similar to Tests and Testability: Apex Structure and Strategy (20)
Sample Gallery: Reference Code and Best Practices for Salesforce DevelopersSalesforce Developers
This document provides an overview of the Salesforce Sample Gallery, which contains sample applications, reference code, and best practices for Salesforce developers. It describes different types of sample apps, including recipe style apps with specific code examples and standalone apps that demonstrate features. The document also outlines upcoming updates to the gallery, such as adding new applications and retiring outdated ones. It promotes benefits like inspiration, learning open source code, and understanding development best practices.
Maximizing Salesforce Lightning Experience and Lightning Component PerformanceSalesforce Developers
The document discusses various factors that affect the performance of Lightning Experience and Lightning Component pages. It outlines six main factors: geographical and network latency, device and browser capabilities, Salesforce org configuration, page complexity, component architecture, and server processing. For each factor, it provides recommendations for how to measure and optimize performance, such as enabling the Salesforce Edge network, limiting the number of components on a page, using conditional rendering, and leveraging caching features. The overall message is that page load time in Lightning Experience is sensitive to these infrastructure, code, and configuration factors.
Last year was eventful for Salesforce Developers - we started with the launch of Lightning Web Components (LWC), open-sourced it, enabled local development, and ended the year by open-sourcing Base Lightning Components. In this webinar, we will explore exciting new developments within Base Components and we will show you how to use open-source Base Components to build engaging applications faster with local development.
In this session we will,
- Spin up a local development environment to build Lightning web components
- Use and customize the base components and recipes to build pages and apps quickly
- Explore the latest features of VS Code developer tooling while coding for a use case
Over the past two months, we’ve announced many new resources for developers at Dreamforce and TrailheaDX India. To learn all about them, watch this video, where we'll explore live demos showcasing the latest updates for Lightning Web Components (LWC), Einstein, Heroku, and a lot more on the Customer 360 Platform.
In this session we,
- Explore key highlights from TrailheaDX India
- Show live demos of generally available features
- Explain how you can benefit from these features
TrailheaDX (TDX) is coming to ‘namma’ Bengaluru in India on Dec 19th and 20th! TrailheaDX India is the conference for everyone who builds on and customises Salesforce — including admins, developers, architects, and partners. This event will have sessions, demos and fun for those just getting started with the platform, as well as for advanced admins, architects and developers.
You might have questions about the event - and to answer your questions Kavindra Patel, known as the father of the Indian Salesforce Community, joins Shashank Srivatsavaya, Head of APAC Developer Relations. Register for our exclusive webinar to:
- Get a sneak peek into exclusive sessions and activities
- Find out who you shouldn’t miss at TrailheaDX India
- Understand what comes with your #TDX19 registration
CodeLive: Build Lightning Web Components faster with Local DevelopmentSalesforce Developers
GitHub repo: https://github.com/satyasekharcvb/lwc-local-dev.git
With the release of a new beta version of Local Development, you can now build Lightning web components faster than ever before! You can now render changes, iterate rapidly, troubleshoot errors, and even connect with data from your org by spinning up a local development server on your machine.
In this session, we build Lightning web components in real time. The exciting new capabilities we showcase will enable you to be an even more productive developer.
In this CodeLive session we:
- Spin up a local development server from the CLI to rapidly edit and view components
- Observe how a rich error handling experience simplifies testing and debugging
- Learn how to proxy data from an org for more context and fine-tuned development
CodeLive: Converting Aura Components to Lightning Web ComponentsSalesforce Developers
This document provides information about a Salesforce webinar on converting Aura components to Lightning Web Components (LWC). The webinar will feature two presenters demonstrating how to convert Aura components to LWC. The document includes forward-looking statements and disclaimers about product availability. It also provides information on asking questions during the webinar and resources for continuing the learning journey with Trailhead and the Trailblazer community.
Earlier this year, we released Lightning Web Components (LWC), a new UI framework based on web standards and optimized for performance and developer productivity. We have now open sourced the Lightning Web Components framework so that anyone can build applications on any platform.
Join our webinar where we'll explore how this framework, based on standard HTML, modern JavaScript (ES6+), and the best of native Web Components, helps you create web components and apps using the stack and tools you prefer.
We recently announced over 300 new features and enhancements at TrailheaDX '19 and for the Summer '19 release. In our Developer Highlights webinar we explore the top features with in-depth demos, including the latest updates for Lightning Web Components (LWC), LWC Open Source, CLI updates, Change Data Capture for external objects, Asynchronous Apex Triggers, Notification Builder and more.
Watch the recording here: https://youtu.be/kmOkk74QiCo
You can watch a recording of the live coding session at https://sforce.co/2IbU3yJ
In the fifth and final webinar of our five part series, we learn how to build Lightning web components for different use cases. We explore how to leverage all of the concepts you’ve learned in this webinar series to create modern apps with Lightning Web Components. We also demonstrate various ways to migrate Aura components to Lightning web components for a seamless transition.
This document discusses Lightning Web Components security and testing. It begins with forward-looking statements and risks related to new functionality, products, and services. It then provides information on debugging code, including using browser tools and debugging in different modes. Finally, it discusses unit testing Lightning Web Components with Jest, including prerequisites, configuration, and an example test file.
LWC Episode 3- Component Communication and Aura InteroperabilitySalesforce Developers
Lightning Web Components gives JavaScript developers a web standards-based path to building apps on the Salesforce Lightning Platform.
In the third episode of our five part series on Lightning Web Components, we cover design considerations and compositions of Lightning Web Components.
This document provides an overview of Lightning Web Components Episode 2 which focuses on working with Salesforce data. It discusses how the Lightning Data Service and UI API are used to retrieve and display Salesforce record data. It also demonstrates how to use wire services to connect Lightning Web Components to Apex methods to retrieve and manipulate data. The document concludes with instructions for configuring Lightning Web Components to be used in the Lightning App Builder.
Lightning Web Components are a JavaScript programming model for building web applications and interfaces that is built on the best of web standards.
Any front-end web developer can get started with LWC and leverage custom elements, and JavaScript APIs to create modern apps and experiences that are fully aware of Salesforce data and processes.
Migrate legacy Salesforce CPQ to Advanced Calculator with the help of JSQCP. With Advanced Calculator, you can boost the runtime of quote creation. Join this webinar to learn what is required for migration - we’ll also walk through JSQCP.
This document discusses techniques for addressing large data volumes (LDV) in Salesforce orgs, including big objects. Big objects are a special type of object designed to store and retrieve large data volumes using big data technology. The document also provides a use case where a company wants to archive closed cases to free up storage space while maintaining access. It recommends using a custom big object to address these needs. The webinar will demonstrate creating and deploying a custom big object and retrieving data using asynchronous SOQL.
Replicate Salesforce Data in Real Time with Change Data CaptureSalesforce Developers
Migrate your batch processing, scheduled ETL, and nightly workloads to event-driven, real-time integrations using Change Data Capture. CDC means data change events are published to an event stream, allowing businesses to have up-to-date information across systems and applications. Join us to learn how to configure Change Data Capture and subscribe to the stream of change events, streamlining your architectures and processes.
This document provides an overview of modern development with Salesforce DX. It discusses using source control and metadata with scratch orgs and the Salesforce CLI for source-driven development. Visual Studio Code is highlighted as an IDE for Salesforce development with features like the Salesforce extension pack. The document contrasts traditional org-based development with the new paradigm of package development where changes are tracked relative to package versions. It demonstrates these concepts with a live demo and encourages attendees to learn more on Trailhead.
Lightning Flow makes it easier for developers to build dynamic process-driven apps with Process Builder and the new Flow Builder. Join us and learn more about how you can get in the Flow!
Integrate CMS Content Into Lightning Communities with CMS ConnectSalesforce Developers
In this webinar we will show you how to display content from external Content Management Systems into Lightning Communities. This lets you take advantage of the Communities framework and help you centralize content in whatever CMS system you have chosen.
HCL Notes and Domino License Cost Reduction in the World of DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-and-domino-license-cost-reduction-in-the-world-of-dlau/
The introduction of DLAU and the CCB & CCX licensing model caused quite a stir in the HCL community. As a Notes and Domino customer, you may have faced challenges with unexpected user counts and license costs. You probably have questions on how this new licensing approach works and how to benefit from it. Most importantly, you likely have budget constraints and want to save money where possible. Don’t worry, we can help with all of this!
We’ll show you how to fix common misconfigurations that cause higher-than-expected user counts, and how to identify accounts which you can deactivate to save money. There are also frequent patterns that can cause unnecessary cost, like using a person document instead of a mail-in for shared mailboxes. We’ll provide examples and solutions for those as well. And naturally we’ll explain the new licensing model.
Join HCL Ambassador Marc Thomas in this webinar with a special guest appearance from Franz Walder. It will give you the tools and know-how to stay on top of what is going on with Domino licensing. You will be able lower your cost through an optimized configuration and keep it low going forward.
These topics will be covered
- Reducing license cost by finding and fixing misconfigurations and superfluous accounts
- How do CCB and CCX licenses really work?
- Understanding the DLAU tool and how to best utilize it
- Tips for common problem areas, like team mailboxes, functional/test users, etc
- Practical examples and best practices to implement right away
Things to Consider When Choosing a Website Developer for your Website | FODUUFODUU
Choosing the right website developer is crucial for your business. This article covers essential factors to consider, including experience, portfolio, technical skills, communication, pricing, reputation & reviews, cost and budget considerations and post-launch support. Make an informed decision to ensure your website meets your business goals.
Best 20 SEO Techniques To Improve Website Visibility In SERPPixlogix Infotech
Boost your website's visibility with proven SEO techniques! Our latest blog dives into essential strategies to enhance your online presence, increase traffic, and rank higher on search engines. From keyword optimization to quality content creation, learn how to make your site stand out in the crowded digital landscape. Discover actionable tips and expert insights to elevate your SEO game.
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc
How does your privacy program stack up against your peers? What challenges are privacy teams tackling and prioritizing in 2024?
In the fifth annual Global Privacy Benchmarks Survey, we asked over 1,800 global privacy professionals and business executives to share their perspectives on the current state of privacy inside and outside of their organizations. This year’s report focused on emerging areas of importance for privacy and compliance professionals, including considerations and implications of Artificial Intelligence (AI) technologies, building brand trust, and different approaches for achieving higher privacy competence scores.
See how organizational priorities and strategic approaches to data security and privacy are evolving around the globe.
This webinar will review:
- The top 10 privacy insights from the fifth annual Global Privacy Benchmarks Survey
- The top challenges for privacy leaders, practitioners, and organizations in 2024
- Key themes to consider in developing and maintaining your privacy program
Infrastructure Challenges in Scaling RAG with Custom AI modelsZilliz
Building Retrieval-Augmented Generation (RAG) systems with open-source and custom AI models is a complex task. This talk explores the challenges in productionizing RAG systems, including retrieval performance, response synthesis, and evaluation. We’ll discuss how to leverage open-source models like text embeddings, language models, and custom fine-tuned models to enhance RAG performance. Additionally, we’ll cover how BentoML can help orchestrate and scale these AI components efficiently, ensuring seamless deployment and management of RAG systems in the cloud.
Have you ever been confused by the myriad of choices offered by AWS for hosting a website or an API?
Lambda, Elastic Beanstalk, Lightsail, Amplify, S3 (and more!) can each host websites + APIs. But which one should we choose?
Which one is cheapest? Which one is fastest? Which one will scale to meet our needs?
Join me in this session as we dive into each AWS hosting service to determine which one is best for your scenario and explain why!
Monitoring and Managing Anomaly Detection on OpenShift.pdfTosin Akinosho
Monitoring and Managing Anomaly Detection on OpenShift
Overview
Dive into the world of anomaly detection on edge devices with our comprehensive hands-on tutorial. This SlideShare presentation will guide you through the entire process, from data collection and model training to edge deployment and real-time monitoring. Perfect for those looking to implement robust anomaly detection systems on resource-constrained IoT/edge devices.
Key Topics Covered
1. Introduction to Anomaly Detection
- Understand the fundamentals of anomaly detection and its importance in identifying unusual behavior or failures in systems.
2. Understanding Edge (IoT)
- Learn about edge computing and IoT, and how they enable real-time data processing and decision-making at the source.
3. What is ArgoCD?
- Discover ArgoCD, a declarative, GitOps continuous delivery tool for Kubernetes, and its role in deploying applications on edge devices.
4. Deployment Using ArgoCD for Edge Devices
- Step-by-step guide on deploying anomaly detection models on edge devices using ArgoCD.
5. Introduction to Apache Kafka and S3
- Explore Apache Kafka for real-time data streaming and Amazon S3 for scalable storage solutions.
6. Viewing Kafka Messages in the Data Lake
- Learn how to view and analyze Kafka messages stored in a data lake for better insights.
7. What is Prometheus?
- Get to know Prometheus, an open-source monitoring and alerting toolkit, and its application in monitoring edge devices.
8. Monitoring Application Metrics with Prometheus
- Detailed instructions on setting up Prometheus to monitor the performance and health of your anomaly detection system.
9. What is Camel K?
- Introduction to Camel K, a lightweight integration framework built on Apache Camel, designed for Kubernetes.
10. Configuring Camel K Integrations for Data Pipelines
- Learn how to configure Camel K for seamless data pipeline integrations in your anomaly detection workflow.
11. What is a Jupyter Notebook?
- Overview of Jupyter Notebooks, an open-source web application for creating and sharing documents with live code, equations, visualizations, and narrative text.
12. Jupyter Notebooks with Code Examples
- Hands-on examples and code snippets in Jupyter Notebooks to help you implement and test anomaly detection models.
CAKE: Sharing Slices of Confidential Data on BlockchainClaudio Di Ciccio
Presented at the CAiSE 2024 Forum, Intelligent Information Systems, June 6th, Limassol, Cyprus.
Synopsis: Cooperative information systems typically involve various entities in a collaborative process within a distributed environment. Blockchain technology offers a mechanism for automating such processes, even when only partial trust exists among participants. The data stored on the blockchain is replicated across all nodes in the network, ensuring accessibility to all participants. While this aspect facilitates traceability, integrity, and persistence, it poses challenges for adopting public blockchains in enterprise settings due to confidentiality issues. In this paper, we present a software tool named Control Access via Key Encryption (CAKE), designed to ensure data confidentiality in scenarios involving public blockchains. After outlining its core components and functionalities, we showcase the application of CAKE in the context of a real-world cyber-security project within the logistics domain.
Paper: https://doi.org/10.1007/978-3-031-61000-4_16
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slackshyamraj55
Discover the seamless integration of RPA (Robotic Process Automation), COMPOSER, and APM with AWS IDP enhanced with Slack notifications. Explore how these technologies converge to streamline workflows, optimize performance, and ensure secure access, all while leveraging the power of AWS IDP and real-time communication via Slack notifications.
“An Outlook of the Ongoing and Future Relationship between Blockchain Technologies and Process-aware Information Systems.” Invited talk at the joint workshop on Blockchain for Information Systems (BC4IS) and Blockchain for Trusted Data Sharing (B4TDS), co-located with with the 36th International Conference on Advanced Information Systems Engineering (CAiSE), 3 June 2024, Limassol, Cyprus.
Ivanti’s Patch Tuesday breakdown goes beyond patching your applications and brings you the intelligence and guidance needed to prioritize where to focus your attention first. Catch early analysis on our Ivanti blog, then join industry expert Chris Goettl for the Patch Tuesday Webinar Event. There we’ll do a deep dive into each of the bulletins and give guidance on the risks associated with the newly-identified vulnerabilities.
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
Tests and Testability: Apex Structure and Strategy
1. Tests and Testability
Apex Structure and Strategy
Stephen Willcock, FinancialForce.com, Director of Product Innovation
@stephenwillcock
2. All about FinancialForce.com
Revolutionizing the Back Office
#1 Accounting, Billing and PSA Apps on the Salesforce platform
▪ Native apps
▪ San Francisco HQ, 595 Market St
▪ R&D in San Francisco, Harrogate UK, and Granada ES
▪ We are hiring! Meet us at Rehab!
3. Tests and Testability - overview
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
4. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
5. Testing strategy
In an ideal world we would test…
An entire system “end-to-end”
Using different types of user
With production data volumes
With complex / varied data profiles
All possible code paths
SIMULTANEOUSLY!
8. Test pyramid
The test pyramid is a concept
developed by Mike Cohn....
[the] essential point is that you
should have many more lowlevel unit tests than high level
end-to-end tests running
through a GUI.
http://martinfowler.com/bliki/TestPyramid.html
9. Test pyramid
Even with good practices on writing them, end-to-end tests are
more prone to non-determinism problems, which can undermine
trust in them.
In short, tests that run end-to-end through the UI are: brittle,
expensive to write, and time consuming to run.
So the pyramid argues that you should do much more
automated testing through unit tests than you should through
traditional GUI based testing.
http://martinfowler.com/bliki/TestPyramid.html
10. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
11. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
12. Unit test principles - what is a unit?
The smallest testable chunk of code
Independent from other units and systems
Uno
15. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
16. Unit test principles - isolation
https://
Uno
Uno
Uno
Uno
@
Uno
Trigger
Validation Rule
Workflow Rule
Uno
Managed Apex
Database
Related Data
…further
dependencies
18. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
19. Unit test principles - saturation
The Force.com platform requires that at least 75% of the Apex
Code in an org be executed via unit tests in order to deploy the
code to production. You shouldn’t consider 75% code coverage to
be an end-goal though
Instead, you should strive to increase the state coverage of
your unit tests
Code has many more possible states than it has lines of code
http://wiki.developerforce.com/page/How_to_Write_Good_Unit_Tests
21. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
22. Unit test principles - expectation
Unit test
•Stakeholder: developers
•Asks: does this code do what it says it will?
System test
•Stakeholder: Business Analyst
•Asks: does this system fulfil my functional requirements?
23. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
24. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
26. Unit test principles - testability
Well structured, Object Oriented code is likely to be testable:
•Encapsulation - well defined inputs and outputs
•Limited class scope
•Limited class size
•Limited method size
TDD
27. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
29. SObject fabrication - the unit
trigger OpportunityLineItems on OpportunityLineItem
(before insert) {
for(OpportunityLineItem item : Trigger.new) {
if(item.Description==null)
item.Description = 'foo';
}
}
30. SObject fabrication - the test
AccountId
StageName
OpportunityLineItem oli = new OpportunityLineItem (
insert new
CloseDate
Description=null );
Opportunity
insert oli;
insert new
oli = [select Description from OpportunityLineItem where
Account
OpportunityId
id=:oli.Id];
UnitPrice
Quantity
insert new
insert new
system.assertEquals('foo',oli.Description);
PricebookEntryId
PricebookEntry
Product2
Select Id from
Pricebook2
31. SObject fabrication - the test
a = new Account(…); insert a;
o = new Opportunity(…); insert o;
pb = [select Id from Pricebook2 … ];
p = new Product2(…); insert p;
pbe = new PricebookEntry(…); insert pbe;
oli = new OpportunityLineItem(…); insert oli;
oli = [select … from OpportunityLineItem …];
system.assertEquals('foo',oli.Description);
32. SObject fabrication - the revised unit
trigger OpportunityLineItems on OpportunityLineItem
(before insert) {
new OpportunityLineItemsTriggerHandler().beforeInsert(
Trigger.new );
}
Testable code:
break up the Trigger
33. SObject fabrication - the revised unit
public class OpportunityLineItemsTriggerHandler {
public void beforeInsert(List<OpportunityLineItem>
items) {
for(OpportunityLineItem item : items) {
if(item.Description==null)
item.Description = 'foo';
}
}
}
Avoid referring to
Trigger variables in the
handler
Testable code:
break up the Trigger
34. SObject fabrication - the revised test
OpportunityLineItem oli = new OpportunityLineItem(
Description=null );
new OpportunityLineItemsTriggerHandler().beforeInsert(
new List<OpportunityLineItem>{oli});
system.assertEquals('foo',oli.Description);
35. SObject fabrication #2 - the unit
public class OpportunityService {
public void adjust(OpportunityLineItem oli) {
oli.UnitPrice += (oli.UnitPrice *
oli.Opportunity.Account.Factor__c);
}
}
36. SObject fabrication #2 - the test
Account a = new Account(Factor__c=0.1);
Opportunity o = new Opportunity(Account=a);
OpportunityLineItem oli = new OpportunityLineItem(
Opportunity=o, UnitPrice=100);
OpportunityService svc = new OpportunityService();
svc.adjust(oli);
system.assertEquals(110,oli.UnitPrice);
37. SObject fabrication - what did we do?
Structured the code to make it easier to test
•Trigger handler / Trigger
Fabricated SObjects (including relationships)
•In-memory
•No database interaction
38. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
39. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
40. Loose type coupling
Use inheritance to “loosen” a relationship
•Interface
•Superclass
Substitute a mock “sibling implementation” during unit tests
42. Loose type coupling - the provider (test subject)
public class Aggregator {
List<OrderController.Item> items;
public void setItems(List<OrderController.Item> items) {
this.items = items; }
public Decimal getSum() {
Decimal result = 0;
for(OrderController.Item item : this.items)
result += item.getValue();
return result;
}
}
43. Loose type coupling - the provider test
List<OrderController.Item> testItems = new
List<OrderController.Item>{ new OrderController.Item(…), … };
Aggregator testAggregator = new Aggregator();
testAggregator.setItems(testItems);
system.assertEquals(123.456,testAggregator.getSum());
44. Loose type coupling - the revised provider
public class Aggregator {
public interface IItem {
Decimal getValue();
}
public void setItems(List<IItem> items) {…}
45. Loose type coupling - the revised provider
public Decimal getSum() {
Decimal result = 0;
for(IItem item : items)
result += item.getValue();
return result;
}
}
46. Loose type coupling - the revised consumer
public controller OrderController {
…
public class Item implements Aggregator.IItem {…}
Aggregator a…
List<Item> items…
a.setItems(items);
Decimal s = a.getSum();
47. Loose type coupling - the revised provider test
class TItem implements Aggregator.IItem {
Decimal value;
TItem(Decimal d) {
value = d;
}
public getValue() {
return value;
}
}
48. Loose type coupling - the revised provider test
List<TItem> testItems = new List<TItem>{ new TItem(100),
new TItem(20.006), new TItem(3.45) };
Aggregator testAggregator = new Aggregator();
testAggregator.setItems(testItems);
system.assertEquals(123.456,testAggregator.getSum());
49. Loose type coupling - what did we do?
OrderController.Item
Aggregator.IItem
TItem
Aggregator
Production
Unit
Test
50. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
51. Dependency Injection
Dependency Injection is all about injecting dependencies, or
simply said, setting relations between instances
Some people refer to it as being the Hollywood principle "Don't
call me, we'll call you”
I prefer calling it the "bugger" principle: "I don't care who
you are, just do what I ask”
http://www.javaranch.com/journal/200709/dependency-injection-unit-testing.
html
55. Dependency injection - provider
public with sharing class OpportunityAdjuster implements
IAdjustOpportunities {
public void adjust(Opportunity o) {
// the actual implementation
// do some stuff to the opp
}
}
56. Dependency injection - mock provider
public with sharing class TOpportunityAdjuster
implements IAdjustOpportunities {
@testVisible Opportunity opp;
@testVisible Boolean calledAdjust;
public void adjust(Opportunity o) {
opp = o;
calledAdjust = true;
}
}
@testVisible
57. Dependency injection - consumer
public class OpportunityController {
IAdjustOpportunities adjuster;
@testVisible OpportunityController(
IAdjustOpportunities a,
ApexPages.StandardController c ) {
this.adjuster = a;
…
}
58. Dependency injection - consumer
public OpportunityController(
ApexPages.StandardController c) {
this(new OpportunityAdjuster(), c);
}
…
public void makeAdjustment() {
adjuster.adjust(opp);
}
59. Dependency injection - consumer test
Opportunity opp = new Opportunity(…);
ApexPages.StandardController sc = new
ApexPages.StandardController(opp);
TOpportunityAdjuster adjuster = new TOpportunityAdjuster();
OpportunityController oc = new
OpportunityController(adjuster, sc);
oc.makeAdjustment();
system.assert(adjuster.calledAdjust);
system.assertEquals(opp,adjuster.opp);
Constructor
injection
60. Dependency injection - what did we do?
• Loosen the coupling to a provider class in a consumer class
• Mock the provider class
• Inject the mock provider implementation into the consumer via
a new @testVisible constructor on the consumer class to test
the consumer class
61. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
62. SObject Decoupler - the unit
public class OpportunitiesTriggerHandler {
public static void afterUpdate(List<Opportunity> items) {
for(Opportunity item : items) {
if(item.IsClosed){
// do something
}
}
}…
}
63. SObject Decoupler - the test
@isTest private class OpportunitiesTriggerHandlerTest {
@isTest static void myTest() {
Opportunity o = new Opportunity(IsClosed=true);
OpportunitiesTriggerHandler handler = new
OpportunitiesTriggerHandler();
Field is not writeable:
handler.afterUpdate(new List<Opportunity>{o});
Opportunity.IsClosed
// test something
}
SObject fabrication limitations:
formula fields, rollup summaries,
system fields, subselects
64. SObject Decoupler - the decoupler
public virtual class OpportunityDecoupler {
public virtual Boolean getIsClosed( Opportunity o ) {
return o.IsClosed;
}
}
65. SObject Decoupler - the test decoupler
public virtual class TOpportunityDecoupler extends
OpportunityDecoupler {
@testVisible Map<Id,Boolean> IsClosedMap =
new Map<Id,Boolean>();
public override Boolean getIsClosed( Opportunity o ) {
return IsClosedMap.get(o.Id);
}
}
66. SObject Decoupler - the revised unit
public class OpportunitiesTriggerHandler {
OpportunityDecoupler decoupler;
@testVisible OpportunitiesTriggerHandler(
OpportunityDecoupler od ) {
this.decoupler = od;
}
public OpportunitiesTriggerHandler() {
this(new OpportunityDecoupler());
}
Constructor
injection
67. SObject Decoupler - the revised unit
public void afterUpdate(List<Opportunity> items) {
for(Opportunity item : items) {
if(decoupler.getIsClosed(item)) {
// do something
}
}
}
}
68. SObject Decoupler - the revised test
@isTest private class OpportunitiesTriggerHandlerTest {
@isTest static void myTest() {
TOpportunityDecoupler decoupler = new
TOpportunityDecoupler();
Opportunity o = new Opportunity(Id =
TestUtility.getFakeId(Opportunity.SObjectType));
decoupler.IsClosedMap.put(o.Id,true);
Fabrication of
SObject IDs
69. SObject Decoupler - the revised test
public with sharing class TestUtility {
static Integer s_num = 1;
}
public static String getFakeId(Schema.SObjectType sot) {
String result = String.valueOf(s_num++);
return sot.getDescribe().getKeyPrefix() +
'0'.repeat(12-result.length()) + result;
}
Fabrication of
SObject IDs
70. SObject Decoupler - the revised test
OpportunitiesTriggerHandler handler = new
OpportunitiesTriggerHandler(decoupler);
handler.afterUpdate(new List<Opportunity>{o});
// test something
}
71. SObject Decoupler - what did we do?
Mechanism for mocking non-writable SObject properties
•Access the SObject properties via a separate virtual class - the
decoupler
•Decoupler subclass mocks access to non-writable SObject
properties
•Inject the decoupler subclass in the test subject constructor
73. Tests and Testability
Testing strategy
• Test pyramid
Unit test principles
• What is a unit?
• Isolation
• Saturation
• Expectation
Unit test techniques
• Testability
77. Adapter - wrapper
public class LockingRuleHandler implements
IHandleLockingRules {
public void handleAfterUpdate(Map<Id,sObject> oldMap,
Map<Id,sObject> newMap) {
LockingRules.LockingRuleHandler.handleTrigger();
}
}
78. Adapter - mock implementation
public class TLockingRuleHandler implements
IHandleLockingRules {
@testVisible Boolean calledHandleAfterUpdate;
public void handleAfterUpdate(Map<Id,sObject> oldMap,
Map<Id,sObject> newMap) {
calledHandleAfterUpdate = true;
}
}
79. Adapter - the unit
public class OpportunitiesTriggerHandler {
IHandleLockingRules lockingRules;
@testVisible OpportunitiesTriggerHandler(
IHandleLockingRules lr ) {
this.lockingRules = lr;
}
public OpportunitiesTriggerHandler() {
this(new LockingRuleHandler());
}
Constructor
injection
80. Adapter - the unit
public void handleAfterUpdate(Map<Id,sObject> oldMap,
Map<Id,sObject> newMap) {
lockingRules.handleAfterUpdate(oldMap, newMap);
}
81. Adapter - the test
Map<Id,Opportunity> oldMap …
Map<Id,Opportunity> newMap …
TLockingRuleHandler lockingRules = new
TLockingRuleHandler();
OpportunitiesTriggerHandler trig = new
OpportunitiesTriggerHandler(lockingRules);
trig.afterUpdate(oldMap,newMap);
system.assert(lockingRules.calledHandleAfterUpdate);
…
82. Adapter - what did we do?
Mock a managed class
•Create an interface defining our expectations of the managed
class
•Adapt the the managed class by wrapping and implementing
the interface
•Mock the production class by implementing the same interface
•Inject the mock implementation during unit test execution
83. In a nutshell…
Unit tests are foundational to an effective Apex testing strategy
Consider testability in the structure / design of your code
Units must be independent to be easily tested
Units can be made independent through fabrication and
substitution of connected resources