SlideShare ist ein Scribd-Unternehmen logo
1 von 14
z
Mutation Testing
Testing your tests to test that they test what you think
they test
Stephen Leigh
Test Manager
Sky Betting and Gaming
z
Why do we write unit tests?
- Fast feedback if code is not behaving in the expected way
- Good for debugging, reducing cost of defects
- A form of documentation
- Encourages better design principles
The most relevant reason for the purposes of mutation testing:
- To ensure that any changes we make don’t accidentally
break the functionality of the existing codebase
z
Why do we write unit tests?
“To ensure that any changes we make don’t accidentally break the
functionality of the existing codebase”
To make sure our changes don’t alter any existing functionality, we
need to be sure our unit tests are exercising this functionality
appropriately.
This is what mutation testing can help with.
z
What is mutation testing?
A mutant is a small change in an application’s source code, e.g.:
Source Code
const isPositive = num => num > 0;
Mutant Source Code
const isPositive = num => num >= 0;
Mutation test tools create a large number of these mutants,
then run unit tests against the edited code
z
Mutation examples
Code Possible mutations
if (x === 3) if (x >= 3)
if (x <= 3)
if (x !== 3)
if (true)
if (false)
if (x === 3) {
k++
}
if (x === 3) {}
if (x === 3) k--
return {token: “c38bf32”} return {}
return null
return {token: “”}
z
Killing mutants
When unit tests are run against the mutant, one of three things
happens:
- At least one unit test fails. This means the mutant has been ‘killed’
and therefore the part of the code that has been changed is
properly covered.
- All unit tests pass. This means the mutant has ‘survived’, and the
changed functionality is not covered by tests.
- Infinite loop/runtime error. This usually means that the mutation
isn’t something that could actually happen, and counts as a kill.
As you might expect, generating hundreds of mutants is very
computationally expensive. Fortunately, it’s all automatically handled
by the mutation testing framework.
Simple example
Source Code
function isPositive(num) {
if (num > 0) {
return true;
} else {
return false;
}
}
Pseudo-unit tests
testPositive() {
assertTrue(isPositive(6))
}
testNegative() {
assertFalse(isPositive(-3))
}
Simple example
Mutated Source Code
function isPositive(num) {
if (num >= 0) {
return true;
} else {
return false;
}
}
Pseudo-unit tests
testPositive() {
assertTrue(isPositive(6))
}
testNegative() {
assertFalse(isPositive(-3))
}
Simple example
Mutated Source Code
function isPositive(num) {
if (num >= 0) {
return true;
} else {
return false;
}
}
Pseudo-unit tests
testPositive() {
assertTrue(isPositive(6))
}
testNegative() {
assertFalse(isPositive(-3))
}
testZero() {
assertFalse(isPositive(0))
}
Mutant killed!
More complex example
Source Code
function handleLogin(request, response)
const {username, password} =
if (!username) {
return response.status(400)
.json({reason: ‘ERR_NO_USERNAME’})
}
if (!password) {
return response.status(400)
.json({reason: ‘ERR_NO_PASSWORD’})
}
}
Pseudo-unit tests
const testRequest = {
body: {} // no username or password
fields
}
const mockResponse = () => ...
testNoUsername() {
handleLogin(testRequest, mockResponse);
expect(mockResponse.calls.single.toBe(400)
);
}
testNoPassword() {
handleLogin(testRequest, mockResponse);
expect(mockResponse.calls.single.toBe(400)
);
}
More complex example
Mutated Source Code
function handleLogin(request, response)
const {username, password} =
if (!username) {
return response.status(400)
.json({reason: ‘ERR_NO_USERNAME’})
}
if (false) {
return response.status(400)
.json({reason: ‘ERR_NO_PASSWORD’})
}
}
Pseudo-unit tests
const testRequest = {
body: {} // no username or password
fields
}
const mockResponse = () => ...
testNoUsername() {
handleLogin(testRequest, mockResponse);
expect(mockResponse.calls.single.toBe(400)
);
}
testNoPassword() {
handleLogin(testRequest, mockResponse);
expect(mockResponse.calls.single.toBe(400)
);
}
More complex example
Mutated Source Code
function handleLogin(request, response)
const {username, password} =
if (!username) {
return response.status(400)
.json({reason: ‘ERR_NO_USERNAME’})
}
if (false) {
return response.status(400)
.json({reason: ‘ERR_NO_PASSWORD’})
}
}
Pseudo-unit tests
const testRequest = {
body: {} // no username or password
fields
}
const mockResponse = () => ...
testNoUsername() {
handleLogin(testRequest, mockResponse);
expect(mockResponse.calls[0].toBe(400));
}
testNoPassword() {
const testRequestUsername = {
body: {
username: “abc”
}
};
handleLogin(testRequestUsername,
mockResponse);Mutant killed!
z
Mutation testing: advantages and disadvantages
Advantages
• More reliable metric than line coverage – actually ensures your unit tests are testing
what they should be, and that they follow all possible lines of logic (cyclomatic
complexity)
• Catches many small and easy-to-miss programming errors, as well as holes in unit
tests that would otherwise go unnoticed
Disadvantages
• Extremely computationally expensive – runs can take several hours, making it
unsuitable to run as part of a standard release process
• Requires brainpower to sort ‘junk’ mutations or unimportant survivors from useful
catches. May be an unfavourable signal-to-noise ratio. In these cases it’s potentially
a more useful process to compare over a period of time, to ensure surviving
mutations don’t start going up dramatically.
z
Suggested Tools
- JavaScript: Stryker
- Java/Kotlin: PITest
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Test Automation Framework Design | www.idexcel.com
Test Automation Framework Design | www.idexcel.comTest Automation Framework Design | www.idexcel.com
Test Automation Framework Design | www.idexcel.comIdexcel Technologies
 
Test Automation Best Practices (with SOA test approach)
Test Automation Best Practices (with SOA test approach)Test Automation Best Practices (with SOA test approach)
Test Automation Best Practices (with SOA test approach)Leonard Fingerman
 
Integration testing
Integration testingIntegration testing
Integration testingVaibhav Dash
 
Software Quality Gate.pptx
Software Quality Gate.pptxSoftware Quality Gate.pptx
Software Quality Gate.pptxssuser702665
 
DevOps Tutorial For Beginners | DevOps Tutorial | DevOps Tools | DevOps Train...
DevOps Tutorial For Beginners | DevOps Tutorial | DevOps Tools | DevOps Train...DevOps Tutorial For Beginners | DevOps Tutorial | DevOps Tools | DevOps Train...
DevOps Tutorial For Beginners | DevOps Tutorial | DevOps Tools | DevOps Train...Simplilearn
 
Role Of Qa And Testing In Agile 1225221397167302 8
Role Of Qa And Testing In Agile 1225221397167302 8Role Of Qa And Testing In Agile 1225221397167302 8
Role Of Qa And Testing In Agile 1225221397167302 8a34sharm
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
USER ACCEPTANCE TESTING
USER ACCEPTANCE TESTINGUSER ACCEPTANCE TESTING
USER ACCEPTANCE TESTINGKADARI SHIVRAJ
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 
Testing in Agile Projects
Testing in Agile ProjectsTesting in Agile Projects
Testing in Agile Projectssriks7
 
Software Quality Assurance
Software Quality AssuranceSoftware Quality Assurance
Software Quality AssuranceSachithra Gayan
 
End to end testing - strategies
End to end testing - strategiesEnd to end testing - strategies
End to end testing - strategiesanuvip
 

Was ist angesagt? (20)

Test Automation Framework Design | www.idexcel.com
Test Automation Framework Design | www.idexcel.comTest Automation Framework Design | www.idexcel.com
Test Automation Framework Design | www.idexcel.com
 
Test Automation Best Practices (with SOA test approach)
Test Automation Best Practices (with SOA test approach)Test Automation Best Practices (with SOA test approach)
Test Automation Best Practices (with SOA test approach)
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Software testing
Software testingSoftware testing
Software testing
 
Integration testing
Integration testingIntegration testing
Integration testing
 
Testing methodology
Testing methodologyTesting methodology
Testing methodology
 
Software Quality Gate.pptx
Software Quality Gate.pptxSoftware Quality Gate.pptx
Software Quality Gate.pptx
 
DevOps Tutorial For Beginners | DevOps Tutorial | DevOps Tools | DevOps Train...
DevOps Tutorial For Beginners | DevOps Tutorial | DevOps Tools | DevOps Train...DevOps Tutorial For Beginners | DevOps Tutorial | DevOps Tools | DevOps Train...
DevOps Tutorial For Beginners | DevOps Tutorial | DevOps Tools | DevOps Train...
 
Test Strategy
Test StrategyTest Strategy
Test Strategy
 
Automation testing
Automation testingAutomation testing
Automation testing
 
Role Of Qa And Testing In Agile 1225221397167302 8
Role Of Qa And Testing In Agile 1225221397167302 8Role Of Qa And Testing In Agile 1225221397167302 8
Role Of Qa And Testing In Agile 1225221397167302 8
 
Manual Testing.
Manual Testing.Manual Testing.
Manual Testing.
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
USER ACCEPTANCE TESTING
USER ACCEPTANCE TESTINGUSER ACCEPTANCE TESTING
USER ACCEPTANCE TESTING
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Testing in Agile Projects
Testing in Agile ProjectsTesting in Agile Projects
Testing in Agile Projects
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Software Quality Assurance
Software Quality AssuranceSoftware Quality Assurance
Software Quality Assurance
 
End to end testing - strategies
End to end testing - strategiesEnd to end testing - strategies
End to end testing - strategies
 
release management
release managementrelease management
release management
 

Ähnlich wie Mutation Testing: Testing your tests

We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimizedWoody Pewitt
 
Unit/Integration Testing using Spock
Unit/Integration Testing using SpockUnit/Integration Testing using Spock
Unit/Integration Testing using SpockAnuj Aneja
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's testsSean P. Floyd
 
Using Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingUsing Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingMike Clement
 
Javascript - Break statement, type conversion, regular expression
Javascript - Break statement, type conversion, regular expressionJavascript - Break statement, type conversion, regular expression
Javascript - Break statement, type conversion, regular expressionShivam gupta
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstituteSuresh Loganatha
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionKent Huang
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Dror Helper
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My HeartBui Kiet
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Spock Framework - Slidecast
Spock Framework - SlidecastSpock Framework - Slidecast
Spock Framework - SlidecastDaniel Kolman
 

Ähnlich wie Mutation Testing: Testing your tests (20)

We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
Unit/Integration Testing using Spock
Unit/Integration Testing using SpockUnit/Integration Testing using Spock
Unit/Integration Testing using Spock
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's tests
 
Using Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit TestingUsing Rhino Mocks for Effective Unit Testing
Using Rhino Mocks for Effective Unit Testing
 
Javascript - Break statement, type conversion, regular expression
Javascript - Break statement, type conversion, regular expressionJavascript - Break statement, type conversion, regular expression
Javascript - Break statement, type conversion, regular expression
 
TDD Training
TDD TrainingTDD Training
TDD Training
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstitute
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Next Level Testing
Next Level TestingNext Level Testing
Next Level Testing
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
Spock Framework - Slidecast
Spock Framework - SlidecastSpock Framework - Slidecast
Spock Framework - Slidecast
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 

Kürzlich hochgeladen

UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 

Kürzlich hochgeladen (20)

UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 

Mutation Testing: Testing your tests

  • 1. z Mutation Testing Testing your tests to test that they test what you think they test Stephen Leigh Test Manager Sky Betting and Gaming
  • 2. z Why do we write unit tests? - Fast feedback if code is not behaving in the expected way - Good for debugging, reducing cost of defects - A form of documentation - Encourages better design principles The most relevant reason for the purposes of mutation testing: - To ensure that any changes we make don’t accidentally break the functionality of the existing codebase
  • 3. z Why do we write unit tests? “To ensure that any changes we make don’t accidentally break the functionality of the existing codebase” To make sure our changes don’t alter any existing functionality, we need to be sure our unit tests are exercising this functionality appropriately. This is what mutation testing can help with.
  • 4. z What is mutation testing? A mutant is a small change in an application’s source code, e.g.: Source Code const isPositive = num => num > 0; Mutant Source Code const isPositive = num => num >= 0; Mutation test tools create a large number of these mutants, then run unit tests against the edited code
  • 5. z Mutation examples Code Possible mutations if (x === 3) if (x >= 3) if (x <= 3) if (x !== 3) if (true) if (false) if (x === 3) { k++ } if (x === 3) {} if (x === 3) k-- return {token: “c38bf32”} return {} return null return {token: “”}
  • 6. z Killing mutants When unit tests are run against the mutant, one of three things happens: - At least one unit test fails. This means the mutant has been ‘killed’ and therefore the part of the code that has been changed is properly covered. - All unit tests pass. This means the mutant has ‘survived’, and the changed functionality is not covered by tests. - Infinite loop/runtime error. This usually means that the mutation isn’t something that could actually happen, and counts as a kill. As you might expect, generating hundreds of mutants is very computationally expensive. Fortunately, it’s all automatically handled by the mutation testing framework.
  • 7. Simple example Source Code function isPositive(num) { if (num > 0) { return true; } else { return false; } } Pseudo-unit tests testPositive() { assertTrue(isPositive(6)) } testNegative() { assertFalse(isPositive(-3)) }
  • 8. Simple example Mutated Source Code function isPositive(num) { if (num >= 0) { return true; } else { return false; } } Pseudo-unit tests testPositive() { assertTrue(isPositive(6)) } testNegative() { assertFalse(isPositive(-3)) }
  • 9. Simple example Mutated Source Code function isPositive(num) { if (num >= 0) { return true; } else { return false; } } Pseudo-unit tests testPositive() { assertTrue(isPositive(6)) } testNegative() { assertFalse(isPositive(-3)) } testZero() { assertFalse(isPositive(0)) } Mutant killed!
  • 10. More complex example Source Code function handleLogin(request, response) const {username, password} = if (!username) { return response.status(400) .json({reason: ‘ERR_NO_USERNAME’}) } if (!password) { return response.status(400) .json({reason: ‘ERR_NO_PASSWORD’}) } } Pseudo-unit tests const testRequest = { body: {} // no username or password fields } const mockResponse = () => ... testNoUsername() { handleLogin(testRequest, mockResponse); expect(mockResponse.calls.single.toBe(400) ); } testNoPassword() { handleLogin(testRequest, mockResponse); expect(mockResponse.calls.single.toBe(400) ); }
  • 11. More complex example Mutated Source Code function handleLogin(request, response) const {username, password} = if (!username) { return response.status(400) .json({reason: ‘ERR_NO_USERNAME’}) } if (false) { return response.status(400) .json({reason: ‘ERR_NO_PASSWORD’}) } } Pseudo-unit tests const testRequest = { body: {} // no username or password fields } const mockResponse = () => ... testNoUsername() { handleLogin(testRequest, mockResponse); expect(mockResponse.calls.single.toBe(400) ); } testNoPassword() { handleLogin(testRequest, mockResponse); expect(mockResponse.calls.single.toBe(400) ); }
  • 12. More complex example Mutated Source Code function handleLogin(request, response) const {username, password} = if (!username) { return response.status(400) .json({reason: ‘ERR_NO_USERNAME’}) } if (false) { return response.status(400) .json({reason: ‘ERR_NO_PASSWORD’}) } } Pseudo-unit tests const testRequest = { body: {} // no username or password fields } const mockResponse = () => ... testNoUsername() { handleLogin(testRequest, mockResponse); expect(mockResponse.calls[0].toBe(400)); } testNoPassword() { const testRequestUsername = { body: { username: “abc” } }; handleLogin(testRequestUsername, mockResponse);Mutant killed!
  • 13. z Mutation testing: advantages and disadvantages Advantages • More reliable metric than line coverage – actually ensures your unit tests are testing what they should be, and that they follow all possible lines of logic (cyclomatic complexity) • Catches many small and easy-to-miss programming errors, as well as holes in unit tests that would otherwise go unnoticed Disadvantages • Extremely computationally expensive – runs can take several hours, making it unsuitable to run as part of a standard release process • Requires brainpower to sort ‘junk’ mutations or unimportant survivors from useful catches. May be an unfavourable signal-to-noise ratio. In these cases it’s potentially a more useful process to compare over a period of time, to ensure surviving mutations don’t start going up dramatically.
  • 14. z Suggested Tools - JavaScript: Stryker - Java/Kotlin: PITest Questions?