This document provides an overview of testing concepts and best practices. It discusses different types of bugs, the benefits of writing unit tests, test types like unit tests and integration tests, testability factors, isolation techniques using test doubles, common mistakes to avoid, and Microsoft Fakes for improving testability. The key points covered are:
- The importance of writing tests to prevent bugs and allow safe refactoring.
- Techniques like dependency injection, interfaces, and seams to make code more testable and allow isolation using stubs, fakes, mocks, and shims.
- Common mistakes for test code like testing multiple features in one test, long test runs without maintenance, lack of negative testing, and unclear
The document provides an agenda for a discussion on thoughtful software design. It covers background topics on software design principles like abstraction, encapsulation, and separation of concerns. It then discusses orienteering designer mindsets and basic design principles like the single responsibility principle and principle of least astonishment. The document also addresses migrating legacy systems to more thoughtful designs and techniques for improving design quality like tearing systems apart into isolated layers and components.
The document discusses QA automation, including challenges like ensuring tests are resilient, simple, and comprehensive. It also discusses solutions like developing an automation framework to write high-level tests and using infrastructure for speed and parallelization. The document recommends considering outsourcing automation by evaluating factors like criticality, expertise needs, and test integration.
This document provides guidance on improving estimates. It discusses expanding one's comfort zone to better understand related processes and people. Common estimation methods are outlined, including analogy, expert judgment, and task breakdown. The document emphasizes the importance of holistic, continuous estimation that considers risks, assumptions, and dependencies. It advises committing to estimates only when requirements are clear and risks are addressed, and avoiding arbitrary padding or unrealistic deadlines. Signs of poor estimates, like unreasonable assumptions or lack of deliverable definition, are identified as "estimate smells" to avoid.
2015.01.09 - Writing Modern Applications for Mobile and WebMarco Parenzan
Traditional programming is quite old (60+ years)
Object Oriented Programming is not so old, but old enough (35+ years)
We can say that OOP is able to satisfy our needs of Modern programming
Modern is not about modern programming principles and paradigms
Modern is about current scenarios in which our programming abilities have to be spent these days
Just 10 years ago (in 2K years) we were focusing on something else
Modern Programming for about modern programming challenges:
- Cloud
- Big Data
- Mobile and Devices
- Internet of Things
Principles
- Application Lifecycle Management
- Scrum
- Maintainable Code
Imperative Modeling
- Don’t tell what you want to do: just do it!
Responsibility Modeling
- Why are you coding? Which is the intention inside every line you write?
Functional Modeling
- Declare what you need! I’ll implement it!
Object Modeling
- Classes are the way to describe model into a domain
Contract Modeling
- Class is not just encapsulation. It’s also declaration of a contract
Interface Modeling
- Class should be implementation only. Interfaces are a better way to describe a contract
Three tier Modeling
- An Architectural model for an application
“Blueprints” Modeling
- Feel free to express yourself…or not? Please refer to some work done by experts!
“No more One” Modeling
- One model DOES NOT FITS for all. Multiple models are needed to single aspects of an application
An introduction to Test-First Behavior-Driven Development, and acceptance testing with Gherkin, with some real-life Gherkin examples. Content created for C# code, but the principles do apply to other languages/environments.
This document contains 151 interview questions related to software testing. The questions cover a wide range of testing topics including definitions of software testing, the difference between various testing types, the testing process, test planning and documentation, defect management, and other quality assurance and development processes. Responses would require in-depth knowledge of software testing practices, tools, and methodologies.
The document discusses why software developers should use FlexUnit, an automated unit testing framework for Flex and ActionScript projects. It notes that developers spend 80% of their time debugging code and that errors found later in the development process can cost 100x more to fix than early errors. FlexUnit allows developers to automate unit tests so that tests can be run continually, finding errors sooner when they are cheaper to fix. Writing automated tests also encourages developers to write better structured, more testable and maintainable code. FlexUnit provides a testing architecture and APIs to facilitate automated unit and integration testing as well as different test runners and listeners to output test results.
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flexmichael.labriola
This document discusses automated testing in Flex. It begins by explaining why automated testing is important, such as reducing costs from software errors and allowing developers to change code without fear of breaking other parts of the project. It then covers topics like writing unit tests, using theories and data points to test over multiple values, and writing integration tests. The document emphasizes that writing testable code is key, and provides some principles for doing so, such as separating construction from application logic and using interfaces. It also discusses using fakes, stubs and mocks to isolate units for testing.
The document provides an agenda for a discussion on thoughtful software design. It covers background topics on software design principles like abstraction, encapsulation, and separation of concerns. It then discusses orienteering designer mindsets and basic design principles like the single responsibility principle and principle of least astonishment. The document also addresses migrating legacy systems to more thoughtful designs and techniques for improving design quality like tearing systems apart into isolated layers and components.
The document discusses QA automation, including challenges like ensuring tests are resilient, simple, and comprehensive. It also discusses solutions like developing an automation framework to write high-level tests and using infrastructure for speed and parallelization. The document recommends considering outsourcing automation by evaluating factors like criticality, expertise needs, and test integration.
This document provides guidance on improving estimates. It discusses expanding one's comfort zone to better understand related processes and people. Common estimation methods are outlined, including analogy, expert judgment, and task breakdown. The document emphasizes the importance of holistic, continuous estimation that considers risks, assumptions, and dependencies. It advises committing to estimates only when requirements are clear and risks are addressed, and avoiding arbitrary padding or unrealistic deadlines. Signs of poor estimates, like unreasonable assumptions or lack of deliverable definition, are identified as "estimate smells" to avoid.
2015.01.09 - Writing Modern Applications for Mobile and WebMarco Parenzan
Traditional programming is quite old (60+ years)
Object Oriented Programming is not so old, but old enough (35+ years)
We can say that OOP is able to satisfy our needs of Modern programming
Modern is not about modern programming principles and paradigms
Modern is about current scenarios in which our programming abilities have to be spent these days
Just 10 years ago (in 2K years) we were focusing on something else
Modern Programming for about modern programming challenges:
- Cloud
- Big Data
- Mobile and Devices
- Internet of Things
Principles
- Application Lifecycle Management
- Scrum
- Maintainable Code
Imperative Modeling
- Don’t tell what you want to do: just do it!
Responsibility Modeling
- Why are you coding? Which is the intention inside every line you write?
Functional Modeling
- Declare what you need! I’ll implement it!
Object Modeling
- Classes are the way to describe model into a domain
Contract Modeling
- Class is not just encapsulation. It’s also declaration of a contract
Interface Modeling
- Class should be implementation only. Interfaces are a better way to describe a contract
Three tier Modeling
- An Architectural model for an application
“Blueprints” Modeling
- Feel free to express yourself…or not? Please refer to some work done by experts!
“No more One” Modeling
- One model DOES NOT FITS for all. Multiple models are needed to single aspects of an application
An introduction to Test-First Behavior-Driven Development, and acceptance testing with Gherkin, with some real-life Gherkin examples. Content created for C# code, but the principles do apply to other languages/environments.
This document contains 151 interview questions related to software testing. The questions cover a wide range of testing topics including definitions of software testing, the difference between various testing types, the testing process, test planning and documentation, defect management, and other quality assurance and development processes. Responses would require in-depth knowledge of software testing practices, tools, and methodologies.
The document discusses why software developers should use FlexUnit, an automated unit testing framework for Flex and ActionScript projects. It notes that developers spend 80% of their time debugging code and that errors found later in the development process can cost 100x more to fix than early errors. FlexUnit allows developers to automate unit tests so that tests can be run continually, finding errors sooner when they are cheaper to fix. Writing automated tests also encourages developers to write better structured, more testable and maintainable code. FlexUnit provides a testing architecture and APIs to facilitate automated unit and integration testing as well as different test runners and listeners to output test results.
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flexmichael.labriola
This document discusses automated testing in Flex. It begins by explaining why automated testing is important, such as reducing costs from software errors and allowing developers to change code without fear of breaking other parts of the project. It then covers topics like writing unit tests, using theories and data points to test over multiple values, and writing integration tests. The document emphasizes that writing testable code is key, and provides some principles for doing so, such as separating construction from application logic and using interfaces. It also discusses using fakes, stubs and mocks to isolate units for testing.
This document describes using unit testing and dependency injection to test modules in isolation. It notes that unit tests can be written as code so they are not forgotten or lost like manual test cases. However, modules may depend on other objects like databases or APIs. To address this, the document recommends using interfaces and dependency injection and mocking dependencies with fake objects so the primary module can be tested without external dependencies. This allows each module to be tested in isolation and for unit tests to serve as technical specifications that can be reused across platforms.
This document introduces Adam Tuliper and Christopher Harrison from Microsoft and provides an overview of their session on implementing Entity Framework with MVC. The session will cover introducing Entity Framework, beginning code first development, managing relationships and transactions, and integrating additional features. Attendees will learn how to use Entity Framework to access and manage data in an MVC application.
Refactoring legacy code driven by tests - ITALuca Minudel
Are you working on code poorly designed or on legacy code that’s hard to test? And you cannot refactor it because there are no tests?
During this Coding Dojo you’ll be assigned a coding challenge in Java, C#, Ruby, JavaScript or Python. You will face the challenge of improving the design and refactoring existing code in order to make it testable and to write unit tests.
We will discuss SOLID principles, the relation between design and TDD, and how this applies to your solution.
Reading list:
Growing Object-Oriented Software, Guided by Tests; Steve Freeman, Nat Pryce
Test Driven Development: By Example; Kent Beck
Working Effectively with Legacy; Michael Feathers
Agile Software Development, Principles, Patterns, and Practices; Robert C. Martin (C++, Java)
Agile Principles, Patterns, and Practices in C#; Robert C. Martin (C#)
H2K Infosys provides online IT training and placement services worldwide. It acknowledges proprietary rights of trademarks and products mentioned in training materials, which are only for students' learning purposes and cannot be used or sold privately. The document contains sample questions from ISTQB Foundation Level certification on topics like test techniques, test levels, and definitions.
This document discusses approaches to acceptance test-driven development (ATDD) and behavior-driven development (BDD). It defines ATDD and BDD, compares them, and outlines best practices like the double loop approach, continuous curation of tests, and ensuring tests are maintained as code. It also discusses test pyramids and different types of tests like unit, integration, acceptance, and how they should be balanced.
The document contains responses to questions about software testing terms and concepts. Key points discussed include:
- Cyclomatic complexity is a white box testing type that analyzes the complexity of code.
- Monkey testing tests software without test cases by randomly interacting with screens and inputs to find bugs.
- Severity refers to a bug's seriousness while priority refers to which bug should be fixed first.
- A login screen bug example is provided where severity is low but priority is high due to usability issues.
- System testing is a type of black box testing that tests the full application and includes functionality, regression, and performance testing.
TDD involves three core unit testing practices: programmer testing responsibility, automated tests, and example-based test cases. Programmer testing responsibility makes unit testing the job of developers. Automated tests execute unit tests as code to provide continuous feedback. Example-based test cases adopt a black-box or example-driven approach to focus on interfaces and examples rather than implementation details. Together these practices form the basis for TDD and help improve code quality through early defect detection.
Tutorial of web application load testing in seliniumKevalkumar Shah
Selinium IDE is a specialized tool for performing functional testing on web applications. It allows users to record test cases consisting of steps like entering URLs, filling forms, and verifying results. These test cases can then be run automatically by Selinium IDE to ensure web applications work as expected. The document provides details on downloading, installing, and using Selinium IDE to create and run test cases for a sample web application.
The document provides an overview of software testing techniques, focusing on black-box testing. It discusses the basics of software testing, including verification and validation practices. It also describes the two main techniques of black-box and white-box testing, as well as six types of testing involving both: unit testing, integration testing, functional testing, system testing, stress testing, and performance testing. Finally, it discusses strategies for writing efficient test cases that can find faults with minimal effort.
This document provides an overview of software testing techniques, including black-box and white-box testing. It discusses the basics of software testing throughout the development lifecycle, including verification to check that the product is being built correctly and validation to ensure the right product is being built. Six types of testing involve both black-box and white-box approaches. The document also describes strategies for writing fewer test cases while still finding faults, and using templates for defined, repeatable test cases.
This document summarizes key aspects of .NET architecture for enterprises. It describes the roles and responsibilities of software architects, principles of architecture like separation of concerns and low coupling/high cohesion, and common architectural patterns. It also outlines common layers in applications like the business layer, services layer, data access layer, and presentation layer, describing what they are, responsibilities, and design patterns associated with each layer. The document provides guidance on how to design maintainable and testable systems with a focus on separation of concerns, low coupling between components, and following architectural best practices.
Manual testing interview question by INFOTECHPravinsinh
The document provides answers to various questions related to manual software testing practices. It discusses key concepts like priority and severity levels of defects, examples of high severity low priority defects. It also covers the basis for test case review, contents of requirements documents, differences between web and client-server application testing, defect life cycle, and techniques for test plan preparation. The document is a guide for manual testers that aims to enhance their understanding of software testing concepts and best practices.
1. The document discusses the concept of "bugs" in software and argues they provide learning opportunities if developers focus on practices to prevent bugs rather than just fixing them after the fact.
2. It explores how learning should be a central part of the software development process, with knowledge embodied in the code and acquired through iterative development, feedback loops, and understanding requirements and domains.
3. Effective design involves all aspects of expressing structure, from initial sketches to code, and code itself represents a formal notation for designing virtual structures.
q A contract specifies the requirements and agreement between a software component and its user. Signature contracts define the name, arguments, and types. Functional contracts use pre- and postconditions to specify effects. Operational contracts address quality characteristics.
q Specifying a sorting contract requires considering signature, functional, and operational aspects. The signature defines the iterator types and value type requirements. Functional contracts must precisely define "sorted" and ensure the result is a permutation of the original. Operational contracts avoid prohibitive complexity like O(N^2) checks.
q Testing is better than assertions for checking functional contracts to avoid performance penalties. Complexity requirements also apply to the sorting implementation itself. A complete contract avoids unintended behaviors and ensures
Awareness of design smells - indicators of common design problems - helps developers or software engineers understand mistakes made while designing and apply design principles for creating high-quality designs. This presentation provides insights gained from performing refactoring in real-world projects to improve refactoring and reduce the time and costs of managing software projects.
This document discusses the value and proper use of code comments. It notes that:
- Comments are a form of code that is not executed but can still impact readability. They should aim to communicate intent rather than be bureaucratic documentation.
- There are differing views on commenting - some advocate for commenting all code, some for no comments, but the best approach is for comments to clarify code intent where it is not obvious.
- Many existing comments are actually useless - things like repeated legal statements, version histories, or comments that simply mirror the code. These do not improve understanding and should be removed.
- The ideal is for code to be as self-documenting as possible through clear structure and
q Functional requirements focus on what a system does and are precisely defined and testable. Operational requirements focus on a system's quality of service and user experience through non-functional aspects like performance, availability, and usability. Developmental requirements focus on a system's quality of implementation from the programmer's perspective through aspects like portability, changeability and comprehensibility. Together, all three types of requirements inform and shape the system.
Building unit tests correctly with visual studio 2013Dror Helper
Unit testing is now considered a mainstream practice, but that does not mean it is as common, pervasive or as well understood as it could or should be. Many programmers struggle with the quality of their tests and with the focus of their code. In this session we’ll learn how to write good unit testing code.
This workshop is about testing the right way. Get a clear view on how to test your code in an efficient and useful way!
This first testing-related workshop is about all aspects of unit testing. Integration testing and TDD will have their own dedicated workshops.
The document discusses code quality and its importance. It defines code quality as code that works functionally, is testable, and is easy to maintain. It identifies good practices such as writing testable code, avoiding complexity, and following principles like DRY. Tools like test frameworks, code coverage tools, static analysis tools, and integrated tools like Sonar can help ensure code quality and catch issues early.
This document discusses best practices for writing unit tests. It emphasizes that unit tests should be easy to understand, trustworthy, and robust. A good unit test only fails if a bug is introduced or requirements change. The document provides examples of well-written unit tests and discusses how to avoid common problems like fragile tests. It stresses the importance of testing only specified functionality, using isolation frameworks to mock dependencies, and not putting test logic in the test. Overall, the document promotes writing "clean tests" to avoid brittle tests and minimize maintenance overhead.
This document describes using unit testing and dependency injection to test modules in isolation. It notes that unit tests can be written as code so they are not forgotten or lost like manual test cases. However, modules may depend on other objects like databases or APIs. To address this, the document recommends using interfaces and dependency injection and mocking dependencies with fake objects so the primary module can be tested without external dependencies. This allows each module to be tested in isolation and for unit tests to serve as technical specifications that can be reused across platforms.
This document introduces Adam Tuliper and Christopher Harrison from Microsoft and provides an overview of their session on implementing Entity Framework with MVC. The session will cover introducing Entity Framework, beginning code first development, managing relationships and transactions, and integrating additional features. Attendees will learn how to use Entity Framework to access and manage data in an MVC application.
Refactoring legacy code driven by tests - ITALuca Minudel
Are you working on code poorly designed or on legacy code that’s hard to test? And you cannot refactor it because there are no tests?
During this Coding Dojo you’ll be assigned a coding challenge in Java, C#, Ruby, JavaScript or Python. You will face the challenge of improving the design and refactoring existing code in order to make it testable and to write unit tests.
We will discuss SOLID principles, the relation between design and TDD, and how this applies to your solution.
Reading list:
Growing Object-Oriented Software, Guided by Tests; Steve Freeman, Nat Pryce
Test Driven Development: By Example; Kent Beck
Working Effectively with Legacy; Michael Feathers
Agile Software Development, Principles, Patterns, and Practices; Robert C. Martin (C++, Java)
Agile Principles, Patterns, and Practices in C#; Robert C. Martin (C#)
H2K Infosys provides online IT training and placement services worldwide. It acknowledges proprietary rights of trademarks and products mentioned in training materials, which are only for students' learning purposes and cannot be used or sold privately. The document contains sample questions from ISTQB Foundation Level certification on topics like test techniques, test levels, and definitions.
This document discusses approaches to acceptance test-driven development (ATDD) and behavior-driven development (BDD). It defines ATDD and BDD, compares them, and outlines best practices like the double loop approach, continuous curation of tests, and ensuring tests are maintained as code. It also discusses test pyramids and different types of tests like unit, integration, acceptance, and how they should be balanced.
The document contains responses to questions about software testing terms and concepts. Key points discussed include:
- Cyclomatic complexity is a white box testing type that analyzes the complexity of code.
- Monkey testing tests software without test cases by randomly interacting with screens and inputs to find bugs.
- Severity refers to a bug's seriousness while priority refers to which bug should be fixed first.
- A login screen bug example is provided where severity is low but priority is high due to usability issues.
- System testing is a type of black box testing that tests the full application and includes functionality, regression, and performance testing.
TDD involves three core unit testing practices: programmer testing responsibility, automated tests, and example-based test cases. Programmer testing responsibility makes unit testing the job of developers. Automated tests execute unit tests as code to provide continuous feedback. Example-based test cases adopt a black-box or example-driven approach to focus on interfaces and examples rather than implementation details. Together these practices form the basis for TDD and help improve code quality through early defect detection.
Tutorial of web application load testing in seliniumKevalkumar Shah
Selinium IDE is a specialized tool for performing functional testing on web applications. It allows users to record test cases consisting of steps like entering URLs, filling forms, and verifying results. These test cases can then be run automatically by Selinium IDE to ensure web applications work as expected. The document provides details on downloading, installing, and using Selinium IDE to create and run test cases for a sample web application.
The document provides an overview of software testing techniques, focusing on black-box testing. It discusses the basics of software testing, including verification and validation practices. It also describes the two main techniques of black-box and white-box testing, as well as six types of testing involving both: unit testing, integration testing, functional testing, system testing, stress testing, and performance testing. Finally, it discusses strategies for writing efficient test cases that can find faults with minimal effort.
This document provides an overview of software testing techniques, including black-box and white-box testing. It discusses the basics of software testing throughout the development lifecycle, including verification to check that the product is being built correctly and validation to ensure the right product is being built. Six types of testing involve both black-box and white-box approaches. The document also describes strategies for writing fewer test cases while still finding faults, and using templates for defined, repeatable test cases.
This document summarizes key aspects of .NET architecture for enterprises. It describes the roles and responsibilities of software architects, principles of architecture like separation of concerns and low coupling/high cohesion, and common architectural patterns. It also outlines common layers in applications like the business layer, services layer, data access layer, and presentation layer, describing what they are, responsibilities, and design patterns associated with each layer. The document provides guidance on how to design maintainable and testable systems with a focus on separation of concerns, low coupling between components, and following architectural best practices.
Manual testing interview question by INFOTECHPravinsinh
The document provides answers to various questions related to manual software testing practices. It discusses key concepts like priority and severity levels of defects, examples of high severity low priority defects. It also covers the basis for test case review, contents of requirements documents, differences between web and client-server application testing, defect life cycle, and techniques for test plan preparation. The document is a guide for manual testers that aims to enhance their understanding of software testing concepts and best practices.
1. The document discusses the concept of "bugs" in software and argues they provide learning opportunities if developers focus on practices to prevent bugs rather than just fixing them after the fact.
2. It explores how learning should be a central part of the software development process, with knowledge embodied in the code and acquired through iterative development, feedback loops, and understanding requirements and domains.
3. Effective design involves all aspects of expressing structure, from initial sketches to code, and code itself represents a formal notation for designing virtual structures.
q A contract specifies the requirements and agreement between a software component and its user. Signature contracts define the name, arguments, and types. Functional contracts use pre- and postconditions to specify effects. Operational contracts address quality characteristics.
q Specifying a sorting contract requires considering signature, functional, and operational aspects. The signature defines the iterator types and value type requirements. Functional contracts must precisely define "sorted" and ensure the result is a permutation of the original. Operational contracts avoid prohibitive complexity like O(N^2) checks.
q Testing is better than assertions for checking functional contracts to avoid performance penalties. Complexity requirements also apply to the sorting implementation itself. A complete contract avoids unintended behaviors and ensures
Awareness of design smells - indicators of common design problems - helps developers or software engineers understand mistakes made while designing and apply design principles for creating high-quality designs. This presentation provides insights gained from performing refactoring in real-world projects to improve refactoring and reduce the time and costs of managing software projects.
This document discusses the value and proper use of code comments. It notes that:
- Comments are a form of code that is not executed but can still impact readability. They should aim to communicate intent rather than be bureaucratic documentation.
- There are differing views on commenting - some advocate for commenting all code, some for no comments, but the best approach is for comments to clarify code intent where it is not obvious.
- Many existing comments are actually useless - things like repeated legal statements, version histories, or comments that simply mirror the code. These do not improve understanding and should be removed.
- The ideal is for code to be as self-documenting as possible through clear structure and
q Functional requirements focus on what a system does and are precisely defined and testable. Operational requirements focus on a system's quality of service and user experience through non-functional aspects like performance, availability, and usability. Developmental requirements focus on a system's quality of implementation from the programmer's perspective through aspects like portability, changeability and comprehensibility. Together, all three types of requirements inform and shape the system.
Building unit tests correctly with visual studio 2013Dror Helper
Unit testing is now considered a mainstream practice, but that does not mean it is as common, pervasive or as well understood as it could or should be. Many programmers struggle with the quality of their tests and with the focus of their code. In this session we’ll learn how to write good unit testing code.
This workshop is about testing the right way. Get a clear view on how to test your code in an efficient and useful way!
This first testing-related workshop is about all aspects of unit testing. Integration testing and TDD will have their own dedicated workshops.
The document discusses code quality and its importance. It defines code quality as code that works functionally, is testable, and is easy to maintain. It identifies good practices such as writing testable code, avoiding complexity, and following principles like DRY. Tools like test frameworks, code coverage tools, static analysis tools, and integrated tools like Sonar can help ensure code quality and catch issues early.
This document discusses best practices for writing unit tests. It emphasizes that unit tests should be easy to understand, trustworthy, and robust. A good unit test only fails if a bug is introduced or requirements change. The document provides examples of well-written unit tests and discusses how to avoid common problems like fragile tests. It stresses the importance of testing only specified functionality, using isolation frameworks to mock dependencies, and not putting test logic in the test. Overall, the document promotes writing "clean tests" to avoid brittle tests and minimize maintenance overhead.
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Comunidade NetPonto
Os Testes são cada vez mais uma necessidade nos projectos de desenvolvimento de software... Sejam eles unitários, de carga ou de "User Interface", uma boa framework de testes ajuda a resolver os problemas mais cedo, de forma mais eficaz e mais barata.
No final da sessão vamos perceber não só para que servem, como são feitos e como o Visual Studio 2010 pode ajudar.
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
The document discusses introducing unit testing to legacy C++ code. It covers choosing a testing framework, writing initial tests and mocks, and various refactoring techniques like wrapping dependencies, extracting components, and adding non-intrusive C seams to facilitate testing. The goal is to incrementally make the code more testable while maintaining functionality through practices like test-driven development.
Ever tried doing Test First Test Driven Development? Ever failed? TDD is not easy to get right. Here's some practical advice on doing BDD and TDD correctly. This presentation attempts to explain to you why, what, and how you should test, tell you about the FIRST principles of tests, the connections of unit testing and the SOLID principles, writing testable code, test doubles, the AAA of unit testing, and some practical ideas about structuring tests.
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Ukraine
16 грудня 2021 року відбувся GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Personal Skill”! Анатолій Сахно (Software Testing Consultant, GlobalLogic) розібрав принципи TDD (розробки, керованої тестами) та приклади їх застосування. Крім того, поговорили про:
- Ефективне використання модульних тестів у повсякденних задачах;
- Використання TDD при розробці тестових фреймворків;
- Застосування принципів TDD при написанні функціональних автотестів.
Більше про захід: https://www.globallogic.com/ua/about/events/globallogic-test-automation-online-techtalk-test-driven-development-as-a-personal-skill/
Приємного перегляду і не забудьте залишити коментар про враження від TechTalk!
Ця активність — частина заходів в рамках GlobalLogic Test Automation Advent Calendar, ще більше заходів та цікавинок за посиланням: https://bit.ly/AdventCalendar_fb
The document discusses introductory concepts and best practices for unit testing, including:
1. Why unit tests are important for reducing bugs, improving design, and making development faster.
2. The different types of tests like unit tests, integration tests, and functional tests.
3. What constitutes a unit test, including that it is small, repeatable, consistent, and fast.
4. An example of writing a "Hello World" unit test in C#.
Unit Testing: The Whys, Whens and Hows discusses unit testing definitions, benefits, and best practices. It covers:
- Defining what constitutes a unit test and different testing styles. Unit tests should be written by developers, run fast, be deterministic, and not integrate multiple areas of code.
- Benefits of unit testing include better code quality, a safety net for refactoring, documentation of functionality, and preventing code from becoming untestable.
- Characteristics of good unit tests like being functionally correct, running independently, running fast, and adding new tests for bugs fixed. Good code is more unit testable through interfaces, contracts, and low dependencies.
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.
The document discusses UI testing techniques for handling complex user interfaces at scale. It provides an overview of different types of tests like unit tests, integration tests, and end-to-end tests. Unit tests allow testing small pieces of functionality in isolation while integration tests verify behavior of small units together. End-to-end tests focus on real user scenarios. The document also covers tools for testing like test runners, assertion libraries, spies, and DOM mocking. It emphasizes writing tests first before coding to catch bugs early (test-driven development). Overall, the document aims to help developers understand options for testing complex UIs at scale.
6 Traits of a Successful Test Automation ArchitectureErdem YILDIRIM
This document discusses 6 traits of a successful test automation architecture:
1. Deciding which test levels to automate by considering factors like efficiency, expected vs unexpected scenarios, and intelligence vs repetitiveness.
2. Design principles for test automation including modularity, reusability, and separation of concerns.
3. Locator strategy which determines whether tests are flaky or robust, prioritizing unique, descriptive locators that are unlikely to change.
4. Methodology such as behavior driven development, test driven development, and continuous testing approaches.
5. Framework and language selection considering project dynamics and technologies. Examples mentioned are Geb, Spock, Groovy, and CodeceptJS.
6.
TDD is now mainstream but a lot people don't know or don't remember what is its purpose. TDD is about software design not testing or catching bug. TDD helps developers to shape and create software with "good" design, what is a "good" design is something that we will discuss in the topic.
This document provides an agenda and overview for a mobile agile testing workshop covering both Android and iOS testing. The Android section covers unit, UI, and API testing tools like JUnit, Espresso, and Postman. It also discusses test-driven development. The iOS section similarly covers unit testing with XCTest, UI testing with XCUI, mocking with Cuckoo, and tools like Postman and Jenkins. The document emphasizes why testing is important for catching bugs, making changes confidently, and extending the lifespan of codebases.
The document discusses Google Test, an open source unit testing framework for C++ that can also be used for testing C code, providing an overview of its features and how to implement unit tests using common patterns like test fixtures, assertions, and death tests to validate expected failures. It also covers best practices for writing effective unit tests, including keeping tests independent, focused, and fast-running.
The document discusses unit testing with the Spock testing framework. It introduces Spock and outlines key concepts like the three pillars of good unit tests, Spock idioms, mocks and stubs, and continuous integration. Spock provides an expressive testing language based on Groovy that makes tests more readable, maintainable and trustworthy. Examples demonstrate how to write feature methods, use blocks, verify interactions, stub implementations, test exceptions, integrate with Spring, and perform HTTP calls and data-driven testing with Spock.
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
Takashi Kobayashi and Hironori Washizaki, "SWEBOK Guide and Future of SE Education," First International Symposium on the Future of Software Engineering (FUSE), June 3-6, 2024, Okinawa, Japan
Unveiling the Advantages of Agile Software Development.pdfbrainerhub1
Learn about Agile Software Development's advantages. Simplify your workflow to spur quicker innovation. Jump right in! We have also discussed the advantages.
Measures in SQL (SIGMOD 2024, Santiago, Chile)Julian Hyde
SQL has attained widespread adoption, but Business Intelligence tools still use their own higher level languages based upon a multidimensional paradigm. Composable calculations are what is missing from SQL, and we propose a new kind of column, called a measure, that attaches a calculation to a table. Like regular tables, tables with measures are composable and closed when used in queries.
SQL-with-measures has the power, conciseness and reusability of multidimensional languages but retains SQL semantics. Measure invocations can be expanded in place to simple, clear SQL.
To define the evaluation semantics for measures, we introduce context-sensitive expressions (a way to evaluate multidimensional expressions that is consistent with existing SQL semantics), a concept called evaluation context, and several operations for setting and modifying the evaluation context.
A talk at SIGMOD, June 9–15, 2024, Santiago, Chile
Authors: Julian Hyde (Google) and John Fremlin (Google)
https://doi.org/10.1145/3626246.3653374
WhatsApp offers simple, reliable, and private messaging and calling services for free worldwide. With end-to-end encryption, your personal messages and calls are secure, ensuring only you and the recipient can access them. Enjoy voice and video calls to stay connected with loved ones or colleagues. Express yourself using stickers, GIFs, or by sharing moments on Status. WhatsApp Business enables global customer outreach, facilitating sales growth and relationship building through showcasing products and services. Stay connected effortlessly with group chats for planning outings with friends or staying updated on family conversations.
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j
Dr. Jesús Barrasa, Head of Solutions Architecture for EMEA, Neo4j
Découvrez les dernières innovations de Neo4j, et notamment les dernières intégrations cloud et les améliorations produits qui font de Neo4j un choix essentiel pour les développeurs qui créent des applications avec des données interconnectées et de l’IA générative.
Atelier - Innover avec l’IA Générative et les graphes de connaissancesNeo4j
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Allez au-delà du battage médiatique autour de l’IA et découvrez des techniques pratiques pour utiliser l’IA de manière responsable à travers les données de votre organisation. Explorez comment utiliser les graphes de connaissances pour augmenter la précision, la transparence et la capacité d’explication dans les systèmes d’IA générative. Vous partirez avec une expérience pratique combinant les relations entre les données et les LLM pour apporter du contexte spécifique à votre domaine et améliorer votre raisonnement.
Amenez votre ordinateur portable et nous vous guiderons sur la mise en place de votre propre pile d’IA générative, en vous fournissant des exemples pratiques et codés pour démarrer en quelques minutes.
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesQuickdice ERP
Explore the seamless transition to e-invoicing with this comprehensive guide tailored for Saudi Arabian businesses. Navigate the process effortlessly with step-by-step instructions designed to streamline implementation and enhance efficiency.
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Microservice Teams - How the cloud changes the way we workSven Peters
A lot of technical challenges and complexity come with building a cloud-native and distributed architecture. The way we develop backend software has fundamentally changed in the last ten years. Managing a microservices architecture demands a lot of us to ensure observability and operational resiliency. But did you also change the way you run your development teams?
Sven will talk about Atlassian’s journey from a monolith to a multi-tenanted architecture and how it affected the way the engineering teams work. You will learn how we shifted to service ownership, moved to more autonomous teams (and its challenges), and established platform and enablement teams.
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j
Dr. Jesús Barrasa, Head of Solutions Architecture for EMEA, Neo4j
Découvrez les dernières innovations de Neo4j, et notamment les dernières intégrations cloud et les améliorations produits qui font de Neo4j un choix essentiel pour les développeurs qui créent des applications avec des données interconnectées et de l’IA générative.
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
4. A Bug’s Life
1 X
500 X
DEV PRODUCTIONQADEV TEST LAB
The cost of a bug can increase 500 times from
development to the production release.
DESIGN
0.01
X
5 X
50 X
5. Ineffective Prevention
We should code fewer bugs
We need a tool that finds all bugs
We should hire more QA people
We should have (manual) test plans
We should refactor (without tests)
There is nothing to do about it
Oops…
6. Effective Prevention
Good Design (complexity & coupling)
High-Level technical documentation
Code Reviews – Fagan, Over The Shoulder, Remote
Pair Programming
Use logs, error logs, e-mail notification, etc.
Write Tests (especially Unit Tests)
11. Benefits of writing Unit Tests
1. Bugs are found (much) earlier.
2. Safer changes/refactoring (regression).
3. Up-to-date technical documentation and
examples.
4. Better low level architecture.
12. I do not write tests because…
I do not know how.
It is not my job. The QA people are paid to do that.
It is not my job. Let the customer figure what’s wrong.
I work with untestable legacy code.
I only develop UI.
It makes it difficult to refactor the code.
Requirements are not clear.
I can test everything manually.
There is no time for that.
13. Anatomy of a Unit Test
Set up the needed
dependencies/para
Select a story (class
method + scenario)
Instantiate the class
Exercise/Stimulus
Run the method
Assert the expected
behavior
[TestClass]
public class CalculatorTest {
[TestMethod]
public void ShouldAddTwoPositiveIntegerNumbers() {
int addendum1 = 1;
int addendum2 = 2;
Calculator calc = new Calculator();
int sum = calc.Add(addendum1, addendum2);
Assert.AreEqual(sum, 3);
}
}
14. On-Field Mission:
Testing The Order Processor
Your Mission, should you choose to accept
it, is to unit test ValidateOrderTotal.
INPUT:
A customer id
OUTPUT:
True is the customer order for next delivery exists and the total
amount is > 0. False otherwise.
OrderProcessor processor = OrderProcessor.GetInstance();
bool isValidOrderTotal = processor
.ValidateOrderTotal("00000345-00000-000056");
15. Mission Impossible?
Mission log:
Attempt # Problem Solution
1 File Not Found Need configuration file
2 Invalid Database Set valid connection string
3 Invalid Ross Customer Id Set valid Ross Customer ID
4 Folder not found The export folder must exists and have
permissions
5 SMPT error Update SMPT configuration with valid server,
credential and set notification email
6 Order Processor Stuck Exception Delete marker file
7 Customer does not have order for next del.
date
Create order in DB for customer
8 What about the following delivery? …
… $#%k! …
… … …$#%k! $#%k!
[TestMethod]
public void CheckCustomerWithValidOrderForNextDeliveryDate() {
OrderProcessor processor = OrderProcessor.GetInstance();
bool IsValidOrderTotal = processor.ValidateOrderTotal("00000345-00000-000056");
Assert.IsTrue(IsValidOrderTotal, "...some error message...");
}
16. Bro! Seriously?!
There should be only one reason for a unit test to fail…
Do you have the configuration file?
What is the database connection
string?
Did you set up the export folder?
Did you set up a valid SMTP server?
Did you delete the marker file?
Will the test work next week?Did you set up the Ross Customer
ID correctly?
Does the customer key exist?
Does the customer have an order
for the next delivery?
Does the customer have an order
for the next delivery?
Did you set up a customer with a
valid order total?
Did you set up a customer with an
invalid order total?
Did you set up a customer with a
valid order total?
Did you set up the maximum
waiting time?
17. Corpus
Delicti
public class OrderProcessor {
private static OrderProcessor _instance = new OrderProcessor();
private bool _isMarkerFilePresent = false;
private int _rossCustomerId = 0;
private string _exportPath = string.Empty;
private OrderProcessor() {
_exportPath = ConfigurationSettings.AppSettings["OrderExportPath"];
_isMarkerFilePresent = IOHelper.CheckMarkerFile(this._exportPath);
_rossCustomerId = Convert.ToInt32(ConfigurationSettings.AppSettings["RossCustomerID"]);
int maxSecs = Convert.ToInt32(ConfigurationSettings.AppSettings["MaxSecsToWait"]);
int secsWaited = 0;
while (_isMarkerFilePresent) {
Thread.Sleep(1000);
secsWaited += 1000;
if (secsWaited > maxSecs) {
string email = DBService.GetRossCustomerEmail(_rossCustomerId);
EmailManager.SendEmail(email, "Order Processor is stuck! Check the marker file!");
throw new Exception("Order Processor is stuck! Check the marker file!");
}
}
IOUtility.CreateMarkerFile(_exportPath, "OrderProcessor.MRK");
}
public static OrderProcessor GetInstance() { return _instance; }
public void ExportOrder(string customerId) { … }
public bool ValidateOrderTotal(string customerId) {
decimal orderTotal = 0;
Order order = DBService.GetOrder(customerId, DateTime.Now);
if (order != null) {
foreach (OrderDetail orderDetail in order.Details) {
orderTotal += orderDetail.TotalAmount;
}
}
return orderTotal>0;
}
20. Testable vs. Untestable
Dependency Injection/Transparency
Interfaces/Factories/IOC
Law Of Demeter
Seams
Single Responsibility/Layered Architecture
Composition
Simple Constructors
Idempotence
Commutativity
Implicit Dependencies
New Operator
Service Locators
Static
Mixed Concerns
Deep Inheritance
Complex Constructors
Singletons, DateTime.Now/Random
Implicit Order (hints: Init, Pre, Post, Cleanup, Load)
21. A Better Point of View
Writing tests requires the code to be
testable.
Refactoring code for testability
requires time, skills and experience.
Before writing code, answer this question:
How would you like to test it?
22. Test First
Tests First = testability + small, well-isolated components
Focus on the API first and implementation later
Where did the database go?
Where is the marker file?
What happened to the configuration?
[TestMethod, TestCategory("Order Validation")]
public void OrderWithTotalAmountGreaterThanZeroShouldBeValid() {
Order order = CreateFakeOrder(totalAmount: 10.0);
IOrderValidation orderValidation = new OrderValidation(order);
bool isValidOrderTotal = orderValidation.IsValidTotal();
Assert.IsTrue(isValidOrderTotal,
"Total order amount > 0 should be valid");
}
[TestMethod, TestCategory("Order Validation")]
public void OrderWithTotalAmountZeroShouldBeInvalid() {
Order order = CreateFakeOrder(totalAmount: 0.0);
IOrderValidation orderValidation = new OrderValidation(order);
bool isValidOrderTotal = orderValidation.IsValidTotal();
Assert.IsFalse(isValidOrderTotal,
"Total order amount = 0 should be invalid");
}
[TestMethod, TestCategory("Order Validation")]
public void EmptyOrderShouldBeInvalid() {
Order order = Order.Empty;
IOrderValidation orderValidation = new OrderValidation(order);
bool isValidOrderTotal = orderValidation.IsValidTotal();
Assert.IsFalse(isValidOrderTotal,
"Empty Order should be invalid");
}
public class OrderValidation : IOrderValidation {
Order _order = Order.Empty;
public OrderValidation(Order order) {
_order = order;
}
public bool IsValidTotal() {
decimal orderTotal = 0M;
if (!_order.IsEmpty()) {
foreach (OrderDetail orderDetail in _order.Details) {
orderTotal += orderDetail.DetailAmount;
}
}
return orderTotal > 0;
}
}
24. Controlling the
Test Environment
A good unit test is like a good scientific
experiment: it isolates as many variables as
possible (these are called control variables)
and then validates or rejects a specific
hypothesis about what happens when the one variable (the
independent variable) changes.
Test Code
System Under
Test (SUT)
Dep. 1
Dep. 2
Dep. NISOLATED TEST
SEAMS
26. Test Doubles
Do you need a real plane?
We do not have a real plane available yet
It takes time and it is expensive to prepare a real
plane (checkup, gas, etc.)
Too dangerous, the plane may crash
If there is an issue it is hard to tell if the problem
was the pilot or the plane
28. Dummy
Dummy objects are passed around but never
actually used. Usually they are just used to fill
parameter lists.
public class DummyPlane implements IPlane {
public DummyPlane() {
// Real simple; nothing to initialize!
}
public int getAltitude() {
throw new RuntimeException("This should never be called!");
}
public int getSpeed() {
throw new RuntimeException("This should never be called!");
}
}
29. Stub/Spy
Stubs provide canned answers to calls
made during the test, usually not
responding at all to anything outside what's programmed in for
the test. Spies can record some information based on how
they were called
public class PlaneStub implements IPlane {
public PlaneStub () {
// Real simple; nothing to initialize!
}
public int getAltitude () {
log.Write(“getAltitude was called”);
return 300;
}
public int getSpeed () {
throw new RuntimeException("This should never be called!");
}
30. }
Fake
Fake objects actually have working
implementations, but usually take some shortcut which makes
them not suitable for production (an In Memory Database is a
good example).
public class FakePlane implements IPlane {
…
public FakePlane (FlightStatus status) {
_flightStatus = status;
}
public int getAltitude () {
return CalculateAltitude(_flightStatus);
}
public int getSpeed () {
return CalculateSpeed(_flightStatus);
}
}
31. Mock
Mocks are pre-programmed with expectations
which form a specification of the calls they are
expected to receive. They can throw an exception if they
receive a call they don't expect and are checked during
verification to ensure they got all the calls they were
expecting.
planeControl = MockControl.createControl(Plane.class);
planeMock = (IPlane) planeControl.getMock();
public void testPilotCheckAltitude() {
Pilot pilot = new Pilot();
planeMock.getAltitude();
planeMock.setReturnValue(300);
planeMock.replay();
pilot.Flight((IPlane) planeMock);
planeControl.verify();
}
33. What is it?
Microsoft Fakes is a code isolation framework that can help you isolate code for
testing by replacing other parts of the application with stubs or shims. It allows
you to test parts of your solution even if other parts of your app haven’t been
implemented or aren’t working yet.
34. Stubs
[TestMethod]
public void
StubAccountOpenPostsInitialBalanceCreditTransaction()
{
// Arrange:
int callCount = 0;
StubITransactionManager stubTM = new StubITransactionManager
{
PostTransactionDecimalTransactionType = (amount, type) =>
{
if (amount == 10m && type == TransactionType.Credit)
{
callCount++;
}
}
};
Account cut = new Account(stubTM);
// Act
cut.Open(10m);
// Assert
Assert.AreEqual<int>(1, callCount);
}
35. Shims (Monkey Patching)
Shims are a feature of Microsoft Fakes that allows creating
unit tests for code that would otherwise not be testable in
isolation. In contrast to Stubs, Shims do not require the
code to be tested be designed in a specific way.
[TestMethod]
public void DateTimeTes()
{
using (ShimsContext.Create())
{
// Arrange:
System.Fakes.ShimDateTime.NowGet = () => { return new
DateTime(2016, 2, 29); };
// Act
int result = MyCode.DoSomethingSpecialOnALeapYear();
// Assert
Assert.AreEqual(100, result);
}
}
37. All-In-One
This is by far the most common mistake among beginners.
It comes in two flavors:
1. Unrelated features tested in the same test class/method
2. Single feature tested across multiple layers
Consequences: when the test fails, it is hard to point out at
what has failed
Long Parking
Tests are written correctly but they are executed rarely
and not maintained
Consequences: obsolete tests do not help preventing
bugs. They could mislead developers who read them to
try to understand the program
38. Where is the negative?
Other common mistake, tests are checking only what
the application should do (positive cases) and not
what it should not do (negative cases). Edge cases
and expected exception are also typically ignored by
beginners.
Consequences: poor coverage due to untested scenarios
Bad Names
Tests methods have names that are too
generic or meaningless. E.g. “reportTest”
or “authenticationTest”
Consequences: when the test fails, it is
not immediately obvious what has failed.
They could mislead developers who read
them to try to understand the program
39. Do not succumb to the Dark Side
Write Unit Tests!
Further Reading
Guide: Writing Testable Code
Exploring The Continuum of Test Doubles
Better Unit Testing with Microsoft Fakes
Videos
Introduction to Unit Testing in .NET
http://dotnet.dzone.com/articles/introduction-unit-testing-net
The Clean Code Talks -- Unit Testing
http://www.youtube.com/watch?v=wEhu57pih5w
GTAC 2010: Lessons Learned from Testability Failures
http://www.youtube.com/watch?v=4CFj5thxYQA