This is a slide set with some information about programmer testing. It includes test doubles, mockit and junit.
Visit http://jpereira.eu/2011/12/03/programming-testing/ for more information. If you want to download these slides, please contact me (find my contacts on my blog)
This document provides an overview and agenda for learning about Junit, Mockito, PowerMock, and Hamcrest for testing purposes. It discusses the goal of becoming familiar with these frameworks and libraries. The agenda covers test structure, using Junit with Spring, Mockito stubs and behavior, PowerMock for private/static methods, and key aspects of unit testing like structure, style, and scope. It also provides examples of using Mockito and PowerMock to mock objects, methods, and interactions for testing.
The document discusses unit testing methods like stubbing and mocking. It introduces Mockito, a mocking framework that makes creating mock objects easier. Mockito allows generating mock objects, setting mock behavior using matchers, and verifying mock interactions. It also discusses partial mocking with spies and cautions against over-specifying mock behavior, which can lead to brittle tests. PowerMock is introduced as an extension to Mockito that enables mocking additional constructs like static methods.
Unit testing tests individual units of source code to determine if they are fit for use. It is different from integration testing, which combines modules, and validation testing, which checks that a system meets specifications. The goal of unit testing is to isolate and test each part of a program to show that individual parts are correct. Unit testing provides benefits such as finding problems early, facilitating automated testing and change, and improving software quality. Guidelines for effective unit testing include knowing the objective of each test, making tests self-sufficient, ensuring tests are deterministic, following naming conventions, duplicating code for readability, testing results not implementation, and using isolation frameworks.
This document provides an overview of unit testing and mocking frameworks. It discusses why we unit test and mock, defines common mocking terminology like mocks, stubs and dummies. It then provides an introduction to the Mockito mocking framework, including its syntax and limitations. Examples are provided to demonstrate mocking with Mockito for a user report generation system.
This document discusses mocks and the Mockito API for creating mocks in tests. It defines mocks as objects that simulate the behavior of real objects. Mocks are useful for avoiding high coupling, promoting high cohesion, and improving test performance. The document then covers the Mockito API in particular, noting that it is easy to use, has excellent documentation, and separates stubbing from verification. Examples are provided of Mockito features like exception handling with matchers. The conclusion recommends Mockito for improving test quality.
Testdriven Development using JUnit and EasyMockschlebu
This document discusses test-driven development using JUnit and EasyMock. It introduces test-driven development and mocking, describes how to define expectations and replay mocks using EasyMock, and provides an example demonstration. The summary emphasizes that test-driven development helps write better tests while removing tediousness, and mocking is a useful tool for unit testing that has some technical limitations.
This document provides an overview of using EasyMock, an open source Java testing framework, to create mock objects for unit testing. It discusses how mocking objects can improve testability by removing dependencies. EasyMock allows specifying expected method calls and return values to simulate object behavior. Tests can then verify mocks were used as expected. The document demonstrates creating mocks, setting expectations, replaying mocks, and verifying expectations with EasyMock.
JUnit is a unit testing framework for Java programming language. It was originally written by Kent Beck and Erich Gamma. Some key points:
- JUnit was one of the first unit testing frameworks for Java and has become the de facto standard.
- It allows writing and running repeatable tests to help find and prevent bugs. Tests are written in plain Java classes and methods.
- JUnit provides annotations like @Test, @Before, @After to identify test methods and set up/tear down methods.
- It includes assertions for validations and will report failures immediately. Tests can be organized into test suites.
This document provides an overview and agenda for learning about Junit, Mockito, PowerMock, and Hamcrest for testing purposes. It discusses the goal of becoming familiar with these frameworks and libraries. The agenda covers test structure, using Junit with Spring, Mockito stubs and behavior, PowerMock for private/static methods, and key aspects of unit testing like structure, style, and scope. It also provides examples of using Mockito and PowerMock to mock objects, methods, and interactions for testing.
The document discusses unit testing methods like stubbing and mocking. It introduces Mockito, a mocking framework that makes creating mock objects easier. Mockito allows generating mock objects, setting mock behavior using matchers, and verifying mock interactions. It also discusses partial mocking with spies and cautions against over-specifying mock behavior, which can lead to brittle tests. PowerMock is introduced as an extension to Mockito that enables mocking additional constructs like static methods.
Unit testing tests individual units of source code to determine if they are fit for use. It is different from integration testing, which combines modules, and validation testing, which checks that a system meets specifications. The goal of unit testing is to isolate and test each part of a program to show that individual parts are correct. Unit testing provides benefits such as finding problems early, facilitating automated testing and change, and improving software quality. Guidelines for effective unit testing include knowing the objective of each test, making tests self-sufficient, ensuring tests are deterministic, following naming conventions, duplicating code for readability, testing results not implementation, and using isolation frameworks.
This document provides an overview of unit testing and mocking frameworks. It discusses why we unit test and mock, defines common mocking terminology like mocks, stubs and dummies. It then provides an introduction to the Mockito mocking framework, including its syntax and limitations. Examples are provided to demonstrate mocking with Mockito for a user report generation system.
This document discusses mocks and the Mockito API for creating mocks in tests. It defines mocks as objects that simulate the behavior of real objects. Mocks are useful for avoiding high coupling, promoting high cohesion, and improving test performance. The document then covers the Mockito API in particular, noting that it is easy to use, has excellent documentation, and separates stubbing from verification. Examples are provided of Mockito features like exception handling with matchers. The conclusion recommends Mockito for improving test quality.
Testdriven Development using JUnit and EasyMockschlebu
This document discusses test-driven development using JUnit and EasyMock. It introduces test-driven development and mocking, describes how to define expectations and replay mocks using EasyMock, and provides an example demonstration. The summary emphasizes that test-driven development helps write better tests while removing tediousness, and mocking is a useful tool for unit testing that has some technical limitations.
This document provides an overview of using EasyMock, an open source Java testing framework, to create mock objects for unit testing. It discusses how mocking objects can improve testability by removing dependencies. EasyMock allows specifying expected method calls and return values to simulate object behavior. Tests can then verify mocks were used as expected. The document demonstrates creating mocks, setting expectations, replaying mocks, and verifying expectations with EasyMock.
JUnit is a unit testing framework for Java programming language. It was originally written by Kent Beck and Erich Gamma. Some key points:
- JUnit was one of the first unit testing frameworks for Java and has become the de facto standard.
- It allows writing and running repeatable tests to help find and prevent bugs. Tests are written in plain Java classes and methods.
- JUnit provides annotations like @Test, @Before, @After to identify test methods and set up/tear down methods.
- It includes assertions for validations and will report failures immediately. Tests can be organized into test suites.
Unit testing involves writing code to test individual units or components of an application to ensure they operate as intended. A unit test targets a specific function or class and ensures the code works correctly. A test suite is a collection of test cases that test a module. Frameworks like JUnit simplify the unit testing process and allow for test automation. JUnit tests are created in the same project structure with a "Test" suffix and use annotations to define test cases and suites. Tests can then be run and results analyzed to measure code coverage.
This document provides an overview of how to use Mockito to create mock objects and define their behavior in tests.
It explains how to create mocks with mock(ClassToMock.class), define return values and exceptions with when(method()).thenReturn()/thenThrow(), and verify mock interactions with verify(mock).method(). It also covers using @Mock annotation and initMocks() to initialize mocks, and matchers like eq() to verify argument matching. The document concludes with some Eclipse IDE tips to help with Mockito development.
Mocking allows you to test classes and methods in isolation by replacing their collaborators with mock objects that simulate the normal environment. EasyMock is a framework for creating mock objects that uses a record/replay approach where you first define the expected behavior of mock objects and then replay the code under test to verify it behaves as expected. Mock objects can be normal, strict, or nice depending on how strictly they enforce the expected behavior and order of method calls.
The presentation contains a definition and survey of the benefits of Unit Testing, and a little coding example to get the feeling of Unit Testing using JUnit, EasyMock and XMLUnit.
Test driven development - JUnit basics and best practicesNarendra Pathai
A presentation covering all the basics of Software Unit testing using JUnit framework. A lot of best practices, myths misconceptions are covered. Naming conventions for test methods and fundamental requirements for doing sustainable Junit testing.
This document provides an introduction to JUnit, a unit testing framework for Java. It discusses why unit testing is important, how to write and organize JUnit tests, how to use assertions and mocks, and how to integrate JUnit with IDEs and build tools like Maven and Ant. Key aspects covered include the benefits of unit testing, the core components and design of JUnit, best practices for test-driven development and test maintenance, and resources for learning more about JUnit.
This document discusses unit testing in Java. It introduces unit testing and the JUnit framework. It explains how to set up a testing environment in Eclipse and describes best practices for writing unit tests. These include avoiding conditional logic and loops, using descriptive method and assertion names, and separating tests by type. Advantages of unit testing include speed, isolation, safety when refactoring, and serving as documentation. Disadvantages include potential high maintenance costs from unnecessary tests. Similar testing frameworks exist for other languages like C#, C++, and Python.
This document provides an overview of GoogleMock, a mocking framework for C++. It defines what a mock object is and why they are useful for testing. GoogleMock allows specifying expectations for mock method calls, including how many times a method will be called and what it will return. It provides matchers to check arguments and actions to define return values or behaviors. The document demonstrates how to write mock classes, set expectations, and use mocks in tests to verify code interactions and behavior.
The document summarizes a presentation on software testing concepts and practices like test-driven development, terminology used in testing, popular tools used for testing, and resources for learning more about testing. The presentation covered topics like unit testing, integration testing, test-driven development principles and practices, popular IDEs, build tools, testing frameworks, mock object libraries, code coverage tools, load testing tools, acceptance testing tools, and continuous integration tools. It also demonstrated testing using an open-source medical record system.
This document provides an overview of unit testing in Java using JUnit and NetBeans. It discusses what unit testing is, why it is important, and how to get started with simple unit testing in Java projects using JUnit and the testing functionality built into NetBeans. Key steps include creating a test class, writing test cases that use JUnit assertion methods, and running tests from within NetBeans.
This document provides an overview of JMockit, a mocking framework for unit testing Java code. It discusses how to install JMockit, use annotations like @Mocked and @Injectable to mock classes and instances, set up expectations to define mocked method return values, partially mock classes by mocking specific methods, mock constructors, and verify mocked method calls were made using verifications. The document also explains how to use JMockit's code coverage reporting and addresses common scenarios for when to use expectations, mockups, constructor mocking, and verifications.
JUnit is an open source unit testing framework for Java applications. It was written by Erich Gamma and Kent Beck and is part of the xUnit family of unit testing frameworks. JUnit allows developers to write test cases that test individual classes and methods. These test cases can be grouped into test suites and run automatically to ensure code meets requirements and to catch errors early in the development process. JUnit includes annotations like @Test to identify test methods and asserts to validate method output. It integrates with development tools like Eclipse to provide test results.
Unit tests exercise individual classes in isolation by replacing collaborators with mock objects. Mocks simplify testing by checking behavior rather than state. Popular mocking libraries like EasyMock and Mockito dynamically generate mocks at test runtime to verify expectations and behavior without manually writing stubs. While classical TDD uses real objects, mockist TDD always uses mocks for collaborators, which can promote looser coupling and interfaces in code design.
This document provides an overview of how to create test classes and methods in JUnit and mock objects using frameworks like PowerMock and EasyMock. It describes how to define a test class that extends TestCase and overrides setUp(), tearDown(), and testXXX() methods. It also explains how PowerMock allows mocking static methods, private methods, final classes/methods by using annotations and bytecode manipulation.
Mockito vs JMockit, battle of the mocking frameworksEndranNL
(Original keynote slides can be found at https://github.com/Endran/PublicSlides)
For years the industry standard of mocking on the JVM has been Mockito. Mockito is a wonderful library that really speeds up your testing by allowing you to create mocks in a very simple way. That being said, it does have its drawbacks, for which different strategies need to be deployed to keep your code testable. The main drawbacks are statics and finals. Final classes cannot be mocked, nor final methods, and also static methods are a no-go. To work with these type of things we need to wrap it, and copy the signature in a non final, non static way.
I have a great adversity against statics, I've devoted an entire post about it, in short; It hides dependencies and brings so little convenience at the costs of its drawbacks. Finals on the other hand have purpose, it helps messaging the goal of a class or method. Java is one of the few languages where classes and methods are open/virtual by default and have to be closed/final by explicit action. In (for example) Kotlin, everything is final by default, if you do not want something to be final, you should use the open keyword.
No matter if you follow the principle of making things final, static or not, if you are using Mockito the decision has been made. This mocking framework demands that everything is non-final, demands that everything is designed to be extended, since it might need to be mocked away. We should be able to improve upon this, and by the name of this post, you should be able to guess which framework will save the day. JMockit will help us with our impediments, and will give some other nifty benefits as well!
This document discusses test driven development and unit testing. It begins with an agenda that includes the importance of unit testing, test driven development techniques, and unit testing in .NET and Eclipse. It then covers topics like the definition of a unit, myths about unit testing, how test driven development works in short cycles, and metrics for test usage. Finally, it discusses techniques like common test patterns, using mock objects, and unit testing frameworks like NUnit, MSTest, Moq and features in Visual Studio and Eclipse.
This document discusses test-driven development and unit testing with JUnit. It covers:
- Writing tests before code using stubs, so code is testable and requirements are clear.
- Key aspects of JUnit like test classes, fixtures, assertions and annotations like @Before, @Test.
- Best practices like testing individual methods, writing simple tests first, and repeating the test-code cycle until all tests pass.
- Features of JUnit in Eclipse like generating test stubs from code and viewing test results.
The overall message is that testing saves significant time versus debugging, helps write better code, and is an essential part of the development process. Tests should cover all requirements and edge cases to
This document discusses different approaches to unit testing with mocks using Mockito. It explains that mocks allow isolating dependencies to test units in isolation. It compares directly mocking dependencies with Mockito's mocking features like stubbing, argument matchers, custom argument matchers, argument capture, and verification. Mockito provides cleaner mocking by separating stubbing from verification and supporting flexible argument matching.
Git is a distributed version control system that was created to be highly scalable, distributed, and handle large projects with many collaborators. It uses a content-addressable model where files and directories are stored as immutable Git objects that are referenced by their SHA-1 hash. Commits represent snapshots of the project and form a directed acyclic graph (DAG). Branches are lightweight pointers to commits. Merging combines changes from branches while resolving any conflicts. Remotes allow collaborating by fetching and pushing changes between repositories. Rebase replays local changes on top of updated remote work to keep a linear history.
Unit testing involves writing code to test individual units or components of an application to ensure they operate as intended. A unit test targets a specific function or class and ensures the code works correctly. A test suite is a collection of test cases that test a module. Frameworks like JUnit simplify the unit testing process and allow for test automation. JUnit tests are created in the same project structure with a "Test" suffix and use annotations to define test cases and suites. Tests can then be run and results analyzed to measure code coverage.
This document provides an overview of how to use Mockito to create mock objects and define their behavior in tests.
It explains how to create mocks with mock(ClassToMock.class), define return values and exceptions with when(method()).thenReturn()/thenThrow(), and verify mock interactions with verify(mock).method(). It also covers using @Mock annotation and initMocks() to initialize mocks, and matchers like eq() to verify argument matching. The document concludes with some Eclipse IDE tips to help with Mockito development.
Mocking allows you to test classes and methods in isolation by replacing their collaborators with mock objects that simulate the normal environment. EasyMock is a framework for creating mock objects that uses a record/replay approach where you first define the expected behavior of mock objects and then replay the code under test to verify it behaves as expected. Mock objects can be normal, strict, or nice depending on how strictly they enforce the expected behavior and order of method calls.
The presentation contains a definition and survey of the benefits of Unit Testing, and a little coding example to get the feeling of Unit Testing using JUnit, EasyMock and XMLUnit.
Test driven development - JUnit basics and best practicesNarendra Pathai
A presentation covering all the basics of Software Unit testing using JUnit framework. A lot of best practices, myths misconceptions are covered. Naming conventions for test methods and fundamental requirements for doing sustainable Junit testing.
This document provides an introduction to JUnit, a unit testing framework for Java. It discusses why unit testing is important, how to write and organize JUnit tests, how to use assertions and mocks, and how to integrate JUnit with IDEs and build tools like Maven and Ant. Key aspects covered include the benefits of unit testing, the core components and design of JUnit, best practices for test-driven development and test maintenance, and resources for learning more about JUnit.
This document discusses unit testing in Java. It introduces unit testing and the JUnit framework. It explains how to set up a testing environment in Eclipse and describes best practices for writing unit tests. These include avoiding conditional logic and loops, using descriptive method and assertion names, and separating tests by type. Advantages of unit testing include speed, isolation, safety when refactoring, and serving as documentation. Disadvantages include potential high maintenance costs from unnecessary tests. Similar testing frameworks exist for other languages like C#, C++, and Python.
This document provides an overview of GoogleMock, a mocking framework for C++. It defines what a mock object is and why they are useful for testing. GoogleMock allows specifying expectations for mock method calls, including how many times a method will be called and what it will return. It provides matchers to check arguments and actions to define return values or behaviors. The document demonstrates how to write mock classes, set expectations, and use mocks in tests to verify code interactions and behavior.
The document summarizes a presentation on software testing concepts and practices like test-driven development, terminology used in testing, popular tools used for testing, and resources for learning more about testing. The presentation covered topics like unit testing, integration testing, test-driven development principles and practices, popular IDEs, build tools, testing frameworks, mock object libraries, code coverage tools, load testing tools, acceptance testing tools, and continuous integration tools. It also demonstrated testing using an open-source medical record system.
This document provides an overview of unit testing in Java using JUnit and NetBeans. It discusses what unit testing is, why it is important, and how to get started with simple unit testing in Java projects using JUnit and the testing functionality built into NetBeans. Key steps include creating a test class, writing test cases that use JUnit assertion methods, and running tests from within NetBeans.
This document provides an overview of JMockit, a mocking framework for unit testing Java code. It discusses how to install JMockit, use annotations like @Mocked and @Injectable to mock classes and instances, set up expectations to define mocked method return values, partially mock classes by mocking specific methods, mock constructors, and verify mocked method calls were made using verifications. The document also explains how to use JMockit's code coverage reporting and addresses common scenarios for when to use expectations, mockups, constructor mocking, and verifications.
JUnit is an open source unit testing framework for Java applications. It was written by Erich Gamma and Kent Beck and is part of the xUnit family of unit testing frameworks. JUnit allows developers to write test cases that test individual classes and methods. These test cases can be grouped into test suites and run automatically to ensure code meets requirements and to catch errors early in the development process. JUnit includes annotations like @Test to identify test methods and asserts to validate method output. It integrates with development tools like Eclipse to provide test results.
Unit tests exercise individual classes in isolation by replacing collaborators with mock objects. Mocks simplify testing by checking behavior rather than state. Popular mocking libraries like EasyMock and Mockito dynamically generate mocks at test runtime to verify expectations and behavior without manually writing stubs. While classical TDD uses real objects, mockist TDD always uses mocks for collaborators, which can promote looser coupling and interfaces in code design.
This document provides an overview of how to create test classes and methods in JUnit and mock objects using frameworks like PowerMock and EasyMock. It describes how to define a test class that extends TestCase and overrides setUp(), tearDown(), and testXXX() methods. It also explains how PowerMock allows mocking static methods, private methods, final classes/methods by using annotations and bytecode manipulation.
Mockito vs JMockit, battle of the mocking frameworksEndranNL
(Original keynote slides can be found at https://github.com/Endran/PublicSlides)
For years the industry standard of mocking on the JVM has been Mockito. Mockito is a wonderful library that really speeds up your testing by allowing you to create mocks in a very simple way. That being said, it does have its drawbacks, for which different strategies need to be deployed to keep your code testable. The main drawbacks are statics and finals. Final classes cannot be mocked, nor final methods, and also static methods are a no-go. To work with these type of things we need to wrap it, and copy the signature in a non final, non static way.
I have a great adversity against statics, I've devoted an entire post about it, in short; It hides dependencies and brings so little convenience at the costs of its drawbacks. Finals on the other hand have purpose, it helps messaging the goal of a class or method. Java is one of the few languages where classes and methods are open/virtual by default and have to be closed/final by explicit action. In (for example) Kotlin, everything is final by default, if you do not want something to be final, you should use the open keyword.
No matter if you follow the principle of making things final, static or not, if you are using Mockito the decision has been made. This mocking framework demands that everything is non-final, demands that everything is designed to be extended, since it might need to be mocked away. We should be able to improve upon this, and by the name of this post, you should be able to guess which framework will save the day. JMockit will help us with our impediments, and will give some other nifty benefits as well!
This document discusses test driven development and unit testing. It begins with an agenda that includes the importance of unit testing, test driven development techniques, and unit testing in .NET and Eclipse. It then covers topics like the definition of a unit, myths about unit testing, how test driven development works in short cycles, and metrics for test usage. Finally, it discusses techniques like common test patterns, using mock objects, and unit testing frameworks like NUnit, MSTest, Moq and features in Visual Studio and Eclipse.
This document discusses test-driven development and unit testing with JUnit. It covers:
- Writing tests before code using stubs, so code is testable and requirements are clear.
- Key aspects of JUnit like test classes, fixtures, assertions and annotations like @Before, @Test.
- Best practices like testing individual methods, writing simple tests first, and repeating the test-code cycle until all tests pass.
- Features of JUnit in Eclipse like generating test stubs from code and viewing test results.
The overall message is that testing saves significant time versus debugging, helps write better code, and is an essential part of the development process. Tests should cover all requirements and edge cases to
This document discusses different approaches to unit testing with mocks using Mockito. It explains that mocks allow isolating dependencies to test units in isolation. It compares directly mocking dependencies with Mockito's mocking features like stubbing, argument matchers, custom argument matchers, argument capture, and verification. Mockito provides cleaner mocking by separating stubbing from verification and supporting flexible argument matching.
Git is a distributed version control system that was created to be highly scalable, distributed, and handle large projects with many collaborators. It uses a content-addressable model where files and directories are stored as immutable Git objects that are referenced by their SHA-1 hash. Commits represent snapshots of the project and form a directed acyclic graph (DAG). Branches are lightweight pointers to commits. Merging combines changes from branches while resolving any conflicts. Remotes allow collaborating by fetching and pushing changes between repositories. Rebase replays local changes on top of updated remote work to keep a linear history.
This document provides an overview of test-driven development (TDD) techniques including unit testing with JUnit, behavior-driven development (BDD) with Cucumber, test automation, and using mock objects with Mockito. It defines TDD and its processes, describes tools like JUnit, Cucumber and Mockito, and provides references for further reading on testing practices.
Mockito a simple, intuitive mocking frameworkPhat VU
The document discusses using Mockito, a mocking framework for Java, to create mocks of dependencies for unit testing. It covers the basics of Mockito including creating and configuring mocks, stubbing return values and exceptions, argument matching, capturing arguments, and verifying mock behavior. The document provides examples of common Mockito usage patterns like Given-When-Then and annotations to simplify mock injection.
This document provides an introduction to JUnit and Mockito for testing Java code. It discusses how to set up JUnit tests with annotations like @Before, @After, and @Test. It also covers using JUnit assertions and test suites. For Mockito, the document discusses how to create and use mock objects to stub behavior and verify interactions. It provides examples of argument matchers and consecutive stubbing in Mockito.
Mockito is a mocking framework for Java that allows developers to focus tests on interactions between objects rather than states. It provides test doubles like mocks and spies to simulate dependencies and verify expected interactions. Mockito allows mocking method calls and configuring return values or exceptions to test different scenarios. It provides default values for unstubbed calls to avoid overspecifying tests.
Unit testing is a method to test individual units of source code to determine if they are fit for use. A unit is the smallest testable part of an application. Unit tests are created by programmers during development. Test-driven development uses tests to drive the design by writing a failing test first, then code to pass the test, and refactoring the code. Unit tests should be isolated, repeatable, fast, self-documenting, and use techniques like dependency injection and mocking dependencies. Benefits of unit testing include instant feedback, promoting modularity, acting as a safety net for changes, and providing documentation.
The document discusses best practices for unit testing, including:
1. Tests should follow a 3 step structure of prepare input, call method, check output. They should be fast, consistent, atomic, and have single responsibility.
2. Tests should isolate the environment, classes, and test instances to avoid dependencies. Mocking is recommended for environment isolation.
3. The best practices aim to make tests independent, fast, and easy to maintain through techniques like mocking and separating test logic from production code.
This document discusses unit and integration testing. It begins by explaining the benefits of testing, such as reducing bugs and allowing safe refactoring. It then describes different types of tests like unit, integration, and database tests. The document focuses on unit testing, explaining how to write and organize unit tests using PHPUnit. It provides examples of test assertions and annotations. It also covers mocking and stubbing dependencies. Finally, it discusses challenges like testing code that relies on external components and provides strategies for database testing.
Unit Testing Concepts and Best PracticesDerek Smith
Unit testing involves writing code to test individual units or components of an application to ensure they perform as expected. The document discusses best practices for unit testing including writing atomic, consistent, self-descriptive tests with clear assertions. Tests should be separated by business module and type and not include conditional logic, loops, or exception handling. Production code should be isolated from test code. The goal of unit testing is to validate that code meets specifications and prevents regressions over time.
Unit testing involves testing individual units or components of code to ensure they work as intended. It focuses on testing small, isolated units of code to check functionality and edge cases. Benefits include faster debugging, development and regression testing. Guidelines for effective unit testing include keeping tests small, automated, independent and focused on the code's public API. Tests should cover a variety of inputs including boundaries and error conditions.
Engaging IV&V Testing Services for Agile ProjectsRavi Kumar
This document discusses agile testing and the role of testers in agile development. It covers topics like the value testers provide, Brian Marick's test categories, challenges with agile testing and strategies to address them, and the role of automation and continuous integration. Key points emphasized are that testers are not obsolete in agile and need to adapt to new ways of testing, defining acceptance criteria, collaborating with developers, automating tests, and providing frequent feedback to the team.
The DevOps Dance - Shift Left, Shift Right - Get It RightInflectra
As more organizations move towards continuous integration (CI) and continuous delivery (CD) with DevOps pipelines becoming the norm, where is the right place to do different kinds and levels of testing? In this presentation, I will provide a blueprint for test managers on how to think about shifting left and shifting right while keeping the overall QA picture and goals in mind.
Agile Testing Leadership Lessons for the Test & QA Professionals
Silicon India Software Testing Conference - SOFTEC - 2 July 2011
Bangalore
Presentation from Speaker: Vaidyanathan Ramalingam,
Director Engineering (Test), Huawei Technologies R&D, Bangalore
Coverage:
1) Waterfall Testing Vs Agile Testing
2) Testing Checklist - 5W & 2H
3) Trade Off Economics in Testing
4) Software Testing Eco System
5) RCA (Root Cause Analysis)
Cotact: rvaidya67@hotmail.com
Linked-In: Vaidyanathan Ramalingam
Vaidyanathan Ramalingam presented key lessons on software testing for test and QA professionals. Some of the highlights included:
1) Comparing waterfall vs agile testing approaches in areas like test requirements, strategy, team structure and test automation.
2) Outlining a testing checklist using the "5 Ws and 2 Hs" (Why, What, When, Who, Where, How, How Long) to plan testing.
3) Discussing trade-off considerations around testing scope, resources and quality goals.
4) Describing the software testing ecosystem involving various stakeholders.
5) Emphasizing the importance of root cause analysis (RCA) at different
Agile Testing Leadership Lessons for the Test & QA Professionals
Silicon India Software Testing Conference - SOFTEC - 2 July 2011
Bangalore
Presentation from Speaker: Vaidyanathan Ramalingam,
Director Engineering (Test), Huawei Technologies R&D, Bangalore
Coverage:
1) Waterfall Testing Vs Agile Testing
2) Testing Checklist - 5W & 2H
3) Trade Off Economics in Testing
4) Software Testing Eco System
5) RCA (Root Cause Analysis)
Agile Testing Leadership Lessons for the Test & QA Professionals
Silicon India Software Testing Conference - SOFTEC - 2 July 2011
Bangalore
Presentation from Speaker: Vaidyanathan Ramalingam,
Director Engineering (Test), Huawei Technologies R&D, Bangalore
Coverage:
1) Waterfall Testing Vs Agile Testing
2) Testing Checklist - 5W & 2H
3) Trade Off Economics in Testing
4) Software Testing Eco System
5) RCA (Root Cause Analysis)
Agile Testing Leadership Lessons for the Test & QA Professionals
Silicon India Software Testing Conference - SOFTEC - 2 July 2011
Bangalore
Presentation from Speaker: Vaidyanathan Ramalingam,
Director Engineering (Test), Huawei Technologies R&D, Bangalore
Coverage:
1) Waterfall Testing Vs Agile Testing
2) Testing Checklist - 5W & 2H
3) Trade Off Economics in Testing
4) Software Testing Eco System
5) RCA (Root Cause Analysis)
Cotact: rvaidya67@hotmail.com
Linked-In: Vaidyanathan Ramalingam
Vaidyanathan Ramalingam presented key lessons on software testing for test and QA professionals. Some of the highlights included:
1) Comparing waterfall vs agile testing approaches. Agile testing focuses on incremental requirements, test strategies, and collaborative teams.
2) Using the "5 Ws and 2 Hs" (why, what, when, where, who, how, how long) as a testing checklist.
3) Discussing tradeoffs around test scope, resources, defects, and timelines that require risk mitigation.
4) Describing a software testing ecosystem with various stakeholders involved in development, management, testing, and more.
5) Emp
Agile Testing Leadership Lessons for the Test & QA Professionals
Silicon India Software Testing Conference - SOFTEC - 2 July 2011
Bangalore
Presentation from Speaker: Vaidyanathan Ramalingam,
Director Engineering (Test), Huawei Technologies R&D, Bangalore
Coverage:
1) Waterfall Testing Vs Agile Testing
2) Testing Checklist - 5W & 2H
3) Trade Off Economics in Testing
4) Software Testing Eco System
5) RCA (Root Cause Analysis)
This document discusses key lessons for leadership in test and QA professions. It covers: 1) Differences between waterfall and agile testing approaches. 2) Using a testing checklist of 5 Ws and 2 Hs. 3) Tradeoffs involved in testing economics and scope. 4) The software testing ecosystem involving various stakeholders. The overall message is on adapting testing strategies to agile environments while maintaining quality.
Vaidyanathan Ramalingam presented key lessons on software testing for test and QA professionals. Some of the highlights included:
1) Comparing waterfall vs agile testing approaches. Agile testing focuses on incremental requirements, test strategies, and collaborative teams.
2) Using the "5 Ws and 2 Hs" (why, what, when, where, who, how, how long) as a testing checklist.
3) Discussing tradeoffs around test scope, resources, defects, and timelines that require risk mitigation.
4) Describing a software testing ecosystem with various stakeholders involved in development, management, testing, and more.
5) Emp
Agile Testing Leadership Lessons for the Test & QA Professionals
Silicon India Software Testing Conference - SOFTEC - 2 July 2011
Bangalore
Presentation from Speaker: Vaidyanathan Ramalingam,
Director Engineering (Test), Huawei Technologies R&D, Bangalore
Coverage:
1) Waterfall Testing Vs Agile Testing
2) Testing Checklist - 5W & 2H
3) Trade Off Economics in Testing
4) Software Testing Eco System
5) RCA (Root Cause Analysis)
Agile Testing Leadership Lessons for the Test & QA Professionals
Silicon India Software Testing Conference - SOFTEC - 2 July 2011
Bangalore
Presentation from Speaker: Vaidyanathan Ramalingam,
Director Engineering (Test), Huawei Technologies R&D, Bangalore
Coverage:
1) Waterfall Testing Vs Agile Testing
2) Testing Checklist - 5W & 2H
3) Trade Off Economics in Testing
4) Software Testing Eco System
5) RCA (Root Cause Analysis)
Cotact: rvaidya67@hotmail.com
Linked-In: Vaidyanathan Ramalingam
Agile Testing Leadership Lessons for the Test & QA Professionals
Silicon India Software Testing Conference - SOFTEC - 2 July 2011
Bangalore
Presentation from Speaker: Vaidyanathan Ramalingam,
Director Engineering (Test), Huawei Technologies R&D, Bangalore
Coverage:
1) Waterfall Testing Vs Agile Testing
2) Testing Checklist - 5W & 2H
3) Trade Off Economics in Testing
4) Software Testing Eco System
5) RCA (Root Cause Analysis)
Agile Testing Leadership Lessons for the Test & QA Professionals
Silicon India Software Testing Conference - SOFTEC - 2 July 2011
Bangalore
Presentation from Speaker: Vaidyanathan Ramalingam,
Director Engineering (Test), Huawei Technologies R&D, Bangalore
Coverage:
1) Waterfall Testing Vs Agile Testing
2) Testing Checklist - 5W & 2H
3) Trade Off Economics in Testing
4) Software Testing Eco System
5) RCA (Root Cause Analysis)
Agile Testing Leadership Lessons for the Test & QA Professionals
Silicon India Software Testing Conference - SOFTEC - 2 July 2011
Bangalore
Presentation from Speaker: Vaidyanathan Ramalingam,
Director Engineering (Test), Huawei Technologies R&D, Bangalore
Coverage:
1) Waterfall Testing Vs Agile Testing
2) Testing Checklist - 5W & 2H
3) Trade Off Economics in Testing
4) Software Testing Eco System
5) RCA (Root Cause Analysis)
Cotact: rvaidya67@hotmail.com
Linked-In: Vaidyanathan Ramalingam
The document discusses the value and importance of testing. It provides examples of actions that reduce a tester's value, such as not properly testing features or communicating issues. It also gives examples that increase value, such as finding defects early, getting them fixed, and preventing reoccurrences. The document recommends methods like scenario design, test data exploration, and test execution planning. It emphasizes that success is measured by finding and fixing critical defects early to prevent repeats.
Do The Right Thing - Empowering Your Test TeamsSmartBear
Margo Visitacion of Forrester Research discusses how empowered testing teams can work effectively with their business counterparts to plan and execute highly focused test cycles that, through a combination of manual and automated testing will assure that the highest quality software is being released.
This document provides an overview of fundamentals of software testing. It discusses the five parts of the fundamental test process in broad chronological order: planning and control, analysis and design, implementation and execution, evaluating exit criteria and reporting, and test closure activities. It also covers topics like regression testing, confirmation testing, the differences between re-testing and regression testing, and the importance of independence in testing.
The document discusses the role of automated testers in both waterfall and agile projects. It notes that while test automation was seen as essential in waterfall, the high costs of licenses, support, and maintenance often outweighed the benefits. In agile, test automation is more effective when developers implement and "pass" acceptance tests themselves rather than delegating testing to separate testers. Having dedicated automated testers risks silos, miscommunication, testers falling behind and an uncritical approach. The document argues developers should automate tests through BDD/ATDD to find defects early and refactor confidently. While testers can help pair and extend tests, developers don't need dedicated automated testers to write good automated tests.
Have you ever been confused by the myriad of choices offered by AWS for hosting a website or an API?
Lambda, Elastic Beanstalk, Lightsail, Amplify, S3 (and more!) can each host websites + APIs. But which one should we choose?
Which one is cheapest? Which one is fastest? Which one will scale to meet our needs?
Join me in this session as we dive into each AWS hosting service to determine which one is best for your scenario and explain why!
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/building-and-scaling-ai-applications-with-the-nx-ai-manager-a-presentation-from-network-optix/
Robin van Emden, Senior Director of Data Science at Network Optix, presents the “Building and Scaling AI Applications with the Nx AI Manager,” tutorial at the May 2024 Embedded Vision Summit.
In this presentation, van Emden covers the basics of scaling edge AI solutions using the Nx tool kit. He emphasizes the process of developing AI models and deploying them globally. He also showcases the conversion of AI models and the creation of effective edge AI pipelines, with a focus on pre-processing, model conversion, selecting the appropriate inference engine for the target hardware and post-processing.
van Emden shows how Nx can simplify the developer’s life and facilitate a rapid transition from concept to production-ready applications.He provides valuable insights into developing scalable and efficient edge AI solutions, with a strong focus on practical implementation.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceIndexBug
Imagine a world where machines not only perform tasks but also learn, adapt, and make decisions. This is the promise of Artificial Intelligence (AI), a technology that's not just enhancing our lives but revolutionizing entire industries.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
GraphRAG for Life Science to increase LLM accuracyTomaz Bratanic
GraphRAG for life science domain, where you retriever information from biomedical knowledge graphs using LLMs to increase the accuracy and performance of generated answers
“An Outlook of the Ongoing and Future Relationship between Blockchain Technologies and Process-aware Information Systems.” Invited talk at the joint workshop on Blockchain for Information Systems (BC4IS) and Blockchain for Trusted Data Sharing (B4TDS), co-located with with the 36th International Conference on Advanced Information Systems Engineering (CAiSE), 3 June 2024, Limassol, Cyprus.
Things to Consider When Choosing a Website Developer for your Website | FODUUFODUU
Choosing the right website developer is crucial for your business. This article covers essential factors to consider, including experience, portfolio, technical skills, communication, pricing, reputation & reviews, cost and budget considerations and post-launch support. Make an informed decision to ensure your website meets your business goals.
OpenID AuthZEN Interop Read Out - AuthorizationDavid Brossard
During Identiverse 2024 and EIC 2024, members of the OpenID AuthZEN WG got together and demoed their authorization endpoints conforming to the AuthZEN API
Your One-Stop Shop for Python Success: Top 10 US Python Development Providersakankshawande
Simplify your search for a reliable Python development partner! This list presents the top 10 trusted US providers offering comprehensive Python development services, ensuring your project's success from conception to completion.
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
Building Production Ready Search Pipelines with Spark and MilvusZilliz
Spark is the widely used ETL tool for processing, indexing and ingesting data to serving stack for search. Milvus is the production-ready open-source vector database. In this talk we will show how to use Spark to process unstructured data to extract vector representations, and push the vectors to Milvus vector database for search serving.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
Best 20 SEO Techniques To Improve Website Visibility In SERPPixlogix Infotech
Boost your website's visibility with proven SEO techniques! Our latest blog dives into essential strategies to enhance your online presence, increase traffic, and rank higher on search engines. From keyword optimization to quality content creation, learn how to make your site stand out in the crowded digital landscape. Discover actionable tips and expert insights to elevate your SEO game.
2. Programmer testing
• What is a Test?
What is a Test?
• Overview of Agile testing quadrants
• What is Test Driven Development
h i i l
• Overview of unit testing and JUnit
• Introduction to Test Doubles and Mockito
• Measure code coverage with Cobertura
Measure code coverage with Cobertura
• References
João Pereira, Sep. 2011 2
3. Programmer testing
• What is a Test?
What is a Test?
• Overview of Agile testing quadrants
• What is Test Driven Development
p
• Overview of unit testing and JUnit
• Introduction to Test Doubles and Mockito
• Measure code coverage with Cobertura
• References
João Pereira, Sep. 2011 3
5. What is a Test?
• Everybody knows what a test is.
Everybody knows what a test is.
– Certify that whatever you do, your system will
always behave as expected
– Your system, also known as System Under Test, or
SUT for short, can be:
• An Human Resources application
li i
• Some layer of a Human Resources application
• One module for a Human Resources application
One module for a Human Resources application
• One object that makes your Human Resources
application work
João Pereira, Sep. 2011 5
6. Programmer testing
• What is a Test?
• Overview of Agile testing quadrants
• What is Test Driven Development
What is Test Driven Development
• Overview of unit testing and JUnit
• Introduction to Test Doubles and Mockito
• Measure code coverage with Cobertura
• References
João Pereira, Sep. 2011 6
7. Agile testing Quadrants
Business Facing Tests
F ti lT t
•Functional Tests •Exploratory Tests
Exploratory Tests
Test that critique t
•Examples •Scenarios
•UAT (User Acceptance
team
•Prototypes
p
•Mock‐ups testing)
ports the t
•Simulations /
•Alpha/Beta releases
Q2 Q3
t that supp
the produc
Q1 Q4
•Unit tests •Performance & Load
•Component test testing
ct
S i T i
Test
•Security Testing
•“ility” Testing
Technology Facing Tests
João Pereira, Sep. 2011 7
8. Purpose of tests
• Business facing tests helps drive
Business facing tests helps drive
development, through constant feedback from
the usage of the product (or parts of the
the usage of the product (or parts of the
product) by the customer team.
• Technology facing tests helps the team
to decide the most appropriate design and
architecture.
João Pereira, Sep. 2011 8
9. Purpose of tests
• Test that critique the product helps the
Test that critique the product helps the
organization to discover improvements to
implement into the product.
implement into the product
• Test that supports the team helps the
team to learn HOW to develop WHAT the
customer wants.
João Pereira, Sep. 2011 9
10. Tests that supports the team
• Are the decisions about design and
Are the decisions about design and
architecture the most appropriate?
• Does the system behave correctly?
Does the system behave correctly?
• Does the user interface meet the expectations
of users? (GUI mockups, wireframes, etc)
f ? (GUI k i f )
João Pereira, Sep. 2011 10
11. Business facing tests
• Is what the customer told us really what the
Is what the customer told us, really what the
customer needs?
• Are we implementing what the customer
Are we implementing what the customer
need?
• A
Are we delivering the business value required
d li i h b i l i d
by the client?
João Pereira, Sep. 2011 11
12. Test that critique the product
• Are there any improvements to make to the
Are there any improvements to make to the
product?
• It’s the product better that the competition?
It s the product better that the competition?
• Is the interface with the users working well?
João Pereira, Sep. 2011 12
13. Technology facing tests
• Is the system fast enough? And Secure?
Is the system fast enough? And Secure?
• It’s reliable and robust?
• Are the non‐functional requirements being
h f i l i b i
met? (maintainability, modularity, reusability,
testability, …)
bili )
• Do we have the right design for extensibility?
• Is our code testable? And reusable?
João Pereira, Sep. 2011 13
14. Agile testing Quadrants
Feedback
Business Facing Tests
Tes
st that critiqu
ts the team
Q Q
Q2 Q3 Test Results
Test Results
Test that support
ue the produ
Q1 Q4
uct
Technology Facing Tests
Feedback
João Pereira, Sep. 2011 14
15. Agile testing Quadrants
Feedback
Business Facing Tests
Tes
st that critiqu
ts the team
•New requirements
•Missing requirements
Improvements
•Improvements Q2 Q3
Q Q
Test that support
ue the produ
•Design Improvements
•Architecture improvements Q1 Q4
uct
Technology Facing Tests
Feedback
João Pereira, Sep. 2011 15
16. How does it helps?
• Agile testing Quadrants help the team to answer
g e test g Quad a ts e p t e tea to a s e
questions like:
– Are we using unit and component tests to help us find
the right design for our application?
– Do we have an automated build process that runs our
automated unit tests for quick feedback?
automated unit tests for quick feedback?
– Do our business‐facing tests help us deliver a product
that matches customers’ expectations?
– Are we capturing the right examples of desired system
behavior? Do we need more? Are we basing our tests
on these examples?
on these examples?
João Pereira, Sep. 2011 16
17. How does it helps?
• More questions:
More questions:
– Do we show prototypes of UIs and reports to the
users before we start coding them?
– Do we budget enough time for exploratory
testing? How do we tackle usability testing? Are
we involving our customers enough?
we involving our customers enough?
– Do we consider technological requirements such
as performance and security early enough in the
as performance and security early enough in the
development cycle? Do we have the right tools to
do “ility” testing?
João Pereira, Sep. 2011 17
18. Programmer testing
• What is a Test?
• Overview of Agile testing quadrants
• What is Test Driven Development
p
• Overview of unit testing and JUnit
• Introduction to Test Doubles and Mockito
• Measure code coverage with Cobertura
• References
João Pereira, Sep. 2011 18
19. TDD in Agile testing Quadrants
Business Facing Tests
F ti lT t
•Functional Tests •Exploratory Tests
Exploratory Tests
Test that critique t
? ?
•Examples •Scenarios
•UAT (User Acceptance
team
•Prototypes
p
•Mock‐ups testing)
ports the t
•Simulations /
•Alpha/Beta releases
Q2 Q3
t that supp
the produc
Q1 Q4
•Unit tests •Performance & Load
?
•Component test testing
?
ct
S i T i
Test
•Security Testing
•“ility” Testing
Technology Facing Tests
João Pereira, Sep. 2011 19
20. Agile testing Quadrants
Business Facing Tests
F ti lT t
•Functional Tests •Exploratory Tests
Exploratory Tests
Test that critique t
•Examples •Scenarios
•UAT (User Acceptance
team
•Prototypes
p
•Mock‐ups testing)
ports the t
•Simulations /
•Alpha/Beta releases
Q2 Q3
t that supp
the produc
Q1 Q4
•Performance & Load
testing
ct
S i T i
Test
•Security Testing
•“ility” Testing
Technology Facing Tests
João Pereira, Sep. 2011 20
21. What is TDD?
A way to approach how we
develop software that is
d l ft th t i
maintainable, testable, reusable
maintainable, testable, reusable
and consistently deliver the
expected business value.
db l
João Pereira, Sep. 2011 21
22. What is TDD?
• Makes you constantly think about what is
Makes you constantly think about what is
expected the software to do.
• Drives and evolves your design and
Drives and evolves your design and
architecture through constant feedback.
• Gi
Gives you the confidence to change and
h fid h d
improve your code.
• As soon you master the technique, the faster
and better you develop
João Pereira, Sep. 2011 22
23. What is TDD?
• A core practice of any agile methodology
A core practice of any agile methodology
• Inspired by the test‐first programming concept
of eXtreme
of eXtreme Programming
• Core concept states that designers write
automated unit tests upfront and run them
d i f d h
throughout the project
• Introduced by Kent Beck in 1999
João Pereira, Sep. 2011 23
24. What is TDD?
Write the test
Refactoring Run the test
Run the test
Yes
Needs
Green
G Green or
refactoring? Red?
Red
Commit
Implement/fix
SUT
Go to the next
feature
João Pereira, Sep. 2011 24
25. What is TDD?
• Make more sense with various processes
Make more sense with various processes ,
techniques and tools:
– Build process
Build process
– Source Code Control System
– Continuous Integration
Continuous Integration
– Information radiators
João Pereira, Sep. 2011 25
26. TDD in context
Check‐in code Information Radiator
Source Code Control
System •Build GREEN. Last commit at
12:44 by jsousa
•Build RED. Last commit at
13:40 by jpereira
•Build GREEN Last commit at
Build GREEN. Last commit at
Team
14:54 by jpereira
•Build GREEN. Last commit at
15:11 by jsousa
•Build GREEN. Last commit at
ts
Run test
Continuous 18:59 by jsousa
18 9 b j
Build
Integration •Build RED. Last commit at
System 09:44 by jpereira
Feedback Build/test information
/
João Pereira, Sep. 2011 26
27. Some tools, for your reference
tools
Popular Source Code Control System in Java World
Popular Continuous Integration System in Java World
João Pereira, Sep. 2011 27
28. Programmer testing
• What is a Test?
• Overview of Agile testing quadrants
• What is Test Driven Development
• Overview of unit testing and JUnit
• Introduction to Test Doubles and Mockito
• Measure code coverage with Cobertura
• References
João Pereira, Sep. 2011 28
29. JUnit in Agile testing Quadrants
Business Facing Tests
F ti lT t
•Functional Tests •Exploratory Tests
Exploratory Tests
Test that critique t
? ?
•Examples •Scenarios
•UAT (User Acceptance
team
•Prototypes
p
•Mock‐ups testing)
ports the t
•Simulations /
•Alpha/Beta releases
Q2 Q3
t that supp
the produc
Q1 Q4
•Unit tests •Performance & Load
?
•Component test testing
?
ct
S i T i
Test
•Security Testing
•“ility” Testing
Technology Facing Tests
João Pereira, Sep. 2011 29
30. JUnit in Agile testing Quadrants
Business Facing Tests
F ti lT t
•Functional Tests •Exploratory Tests
Exploratory Tests
Test that critique t
•Examples •Scenarios
•UAT (User Acceptance
team
•Prototypes
p
•Mock‐ups testing)
ports the t
•Simulations /
•Alpha/Beta releases
Q2 Q3
t that supp
the produc
Q1 Q4
•Performance & Load
•Unit testing testing
•Component test
Component test
ct
S i T i
Test
•Security Testing
•“ility” Testing
Technology Facing Tests
João Pereira, Sep. 2011 30
32. What is Unit Testing
An attitude of developers that
A i d fd l h
strive for high quality code!
strive for high quality code!
João Pereira, Sep. 2011 32
33. What is Unit Testing
• Small pieces of code are tested in isolation
Small pieces of code are tested in isolation
from the rest of the system
• Generally don’t care about the interaction
Generally, don t care about the interaction
with other classes
Don t Test
Don’t Test
João Pereira, Sep. 2011 33
34. What is Unit Testing
• Helps you to think about simple designs with
Helps you to think about simple designs with
some OO Principles and best practice in mind:
Encapsulate what varies, program to interfaces,
Encapsulate what varies, program to interfaces,
Single Responsibility Principle, Open Closed Principle,
Don’t Repeat Yourself Principle,…
• Helps you think about what the system should
do and how it should do it.
João Pereira, Sep. 2011 34
35. What is Unit Testing
• Pre‐condition for refactoring*. Would you
Pre condition for refactoring Would you
change a line of production code without
knowing the change s side effects?
knowing the change’s side effects?
*Refactoring is the process of changing a software
system in such a way that it does not alter the
external behavior of the code yet improves its
external behavior of the code yet improves its
internal structure. It is a disciplined way to clean
up code that minimizes the chances of introducing
bugs – in “Refactoring: Improving the design of
existing code”
Martin Fowler
João Pereira, Sep. 2011 35
36. What is Unit Testing
• Generally there is a suite of tests for a single
Generally, there is a suite of tests for a single
class (the System Under Test, or SUT for short)
• Every line of SUT’s code is tested during the
Every line of SUT s code is tested during the
execution of all tests in the suite
A Suite of tests is a powerful bug detector
that decapitates the time it takes to find
bugs – i “R f t i
b in “Refactoring: Improving the
I i th
design of existing code”
Martin Fowler
Martin Fowler
João Pereira, Sep. 2011 36
38. What is JUnit?
“JUnit is a simple framework to write repeatable tests. It is an
instance of the xUnit architecture for unit testing
instance of the xUnit architecture for unit testing
frameworks.”
Erich Gamma
Kent Beck
João Pereira, Sep. 2011 38
39. What is JUnit?
• xUnit is the family name given to a bunch of
is the family name given to a bunch of
testing frameworks that have become widely
known amongst software developers
known amongst software developers
• Origins from Kent Beck paper: “Simple
Smalltalk Testing: With Patterns
Smalltalk Testing: With Patterns”
‐ http://www.xprogramming.com/testfram.htm
João Pereira, Sep. 2011 39
40. Lifecycle of an JUnit Test Class
Load suite fixtures Load test fixtures
Setup suite resources
Setup suite resources Run Test
Setup test resources
Setup test resources
Clear test fixtures
Clear test fixtures
Next Test
N
Release test resources
Yes More
Tests?
No
Clear suite fixtures
End
Release suite resources
João Pereira, Sep. 2011 40
41. Anatomy of an JUnit Test (version 4.x)
4 x)
public class GreetingsTest {
1 @BeforeClass void setupTest() { setupTest
public static 1
System.out.println("setupTest");
}
@Before 2 setupTestCase
2 public void setupTestCase() {
System.out.println("setupTestCase");
} 3 testGreetingsWithNullName
@Test
3 public void testGreetingsWithNullName() {
System.out.println("testGreetingsWithNullName"); 5 tearDownTestCase
}
@ est
@Test
4 public void testGreetingsWithValidName() { 2 setupTestCase
System.out.println("testGreetingsWithValidName");
}
@After 4 testGreetingsWithValidName
5 public void tearDownTestCase() {
System.out.println("tearDownTestCase");
} 5 tearDownTestCase
@AfterClass
6 public static void tearDownTest() {
System.out.println("tearDownTest"); 6 tearDownTest
}
}
João Pereira, Sep. 2011 41
42. Anatomy of an JUnit Test (version 4.x)
4 x)
• Simple POJO (Plain Old Java Object)
Simple POJO (Plain Old Java Object)
• Use of annotations to declare testing instructions
• Basic annotations:
Basic annotations:
– @BeforeClass – Runs before the first test
execution
– @Before – Runs before every test execution
– @Test – Run as a test
Run as a test
– @After – Runs after every test execution
– @AfterClass – Runs after last test execution
@ te C ass u s a te ast test e ecut o
João Pereira, Sep. 2011 42
43. JUnit Quick Start (version 4.x)
4 x)
• In your test class, import statically the Assert class
In your test class, import statically the Assert class
import static org.junit.Assert.*;
• Create the test methods Give a human
Create the test methods. Give a human
understandable name to the test. Annotate the
method with @org.junit.Test
et od t @o g.ju t. est
@Test
public void testAddFundsToAccount() {
//test
}
@Test
public void testCannotWithdrawFromAccountWhenNotEnoughFunds() {
//Test
}
João Pereira, Sep. 2011 43
44. JUnit Quick Start (version 4.x)
4 x)
• Exercise the SUT, and use one of the available
Exercise the SUT, and use one of the available
assertXXX methods, available in class
org.junit.Assert, to verify the results.
• Example:
assertNotNull("this should be true", sut.findDoorUnit("name"));
• Full list of assertXXX methods:
– http://junit.sourceforge.net/javadoc/
João Pereira, Sep. 2011 44
45. JUnit Quick Start (version 4.x)
4 x)
• Verify that a given exception is throw
Verify that a given exception is throw
@T t(expected=NullPointerException.class)
@Test( t d N llP i t E ti l
public void testShouldThrowNPE() {
Object dummyNullObject = null;
dummyNullObject.toString();
y j g();
}
João Pereira, Sep. 2011 45
46. JUnit Quick Start (version 4.x)
4 x)
• Verify if a test is taking more than x
Verify if a test is taking more than x
milliseconds to complete. Used for early
detection of performance problems.
@Test(timeout=1000)
public void testShouldCompleteAlgortithmInLessThanOneSecond() {
//Some complex algorithm running on a complex data structure
}
João Pereira, Sep. 2011 46
47. Test Fixtures
• Use Creation Methods to generate test data
Use Creation Methods to generate test data.
• Example:
p
public void setupTests() {
p
//Some sophisticated test data factory
List<Door> testDoors = TestDataFactory.<Door>generateTestData(10);
for (Door door: testDoors) {
door.save();
}
}
public class TestDataFactory {
/**
* Create a list ob objects of type T
* @param i the number of instances to create
* @return a list of objects of type T
*/
public static <T> List<T> generateTestData(int i) {
//Creational Logic goes here…
}
}
João Pereira, Sep. 2011 47
48. Test Fixtures
• Use YAML to statically represent test data and
y p
load it into your test, with snakeyaml
(http://snakeyaml.org)
• Example
testData.yaml
DoorOne:
name: The door one
defaultCode: 18siks99
DoorTwo:
name: Other door
defaultCode: 27shs7k
public void setupTestData() throws FileNotFoundException {
//Magically is loaded...
YamlAdapter yaml = new YamlAdapter();
List<Door> doors = yaml.<Door>loadData(new FileInputStream("/testData.yaml"));
//rest of the setup
}
João Pereira, Sep. 2011 48
49. Want to lean more about JUnit and
Unit Testing?
• In the web:
In the web:
– xUnit Patterns: http://xunitpatterns.com
– JUnit: http://junit sourceforge net
JUnit: http://junit.sourceforge.net
• Books:
–JUnit In Action
João Pereira, Sep. 2011 49
50. Programmer testing
• What is a Test?
• Overview of Agile testing quadrants
• What is Test Driven Development
• Overview of unit testing and JUnit
• Introduction to Test Doubles and Mockito
• Measure code coverage with Cobertura
• References
João Pereira, Sep. 2011 50
51. Revisiting what Unit Testing is….
Small pieces of code are tested in
isolation from the rest of the system.
Generally, don’t care about the
interaction with other classes.
interaction with other classes
Don’t Test
João Pereira, Sep. 2011 51
52. Testing in Isolation
Testing in Isolation ?
How we deal with these dependencies ?
João Pereira, Sep. 2011 52
53. Testing in isolation
• Generally the SUT depends on other
Generally, the SUT depends on other
components, or the so called depend‐on
component (DOC, for short) in xUnit
component (DOC for short) in xUnit Patterns
DOCs
SUT
João Pereira, Sep. 2011 53
54. Testing in isolation
• DOCs may not be available yet or do not
DOCs may not be available yet, or do not
produce the results we want for our test.
• Executing DOC code may result in undesirable
Executing DOC code may result in undesirable
side effects. Ex: DOC may connect to a
production DB and alter production data.
production DB and alter production data
• Running tests for a SUT that uses all DOCs is
like running integration tests and can be very
lik i i i d b
slow. It’s not the purpose of unit testing!!
João Pereira, Sep. 2011 54
55. Testing in isolation
• DOCs may not be available yet or do not
DOCs may not be available yet, or do not
produce the results we want for our test.
• Executing DOCit T may result ldundesirable
Unit Tests should
U code t h in
Executing DOC code may result in undesirable
side effects. Ex: DOC may connect to a
g alter production data
give instant
production DB and alter production data.
production DB and
feedback!
• Running tests for a SUT that uses all DOCs is
like running integration tests and can be very
lik i i i d b
slow. It’s not the purpose of unit testing!!
João Pereira, Sep. 2011 55
56. Testing in isolation
How can we test The SUT without the DOC ?
João Pereira, Sep. 2011 56
57. Testing in isolation
How can we test the SUT without the DOC?
How can we test the SUT without the DOC?
We can replace these DOCs by “test‐
spec f c equ a e ts
specific equivalents”
João Pereira, Sep. 2011 57
58. Testing in isolation
• Replace the DOCs by Test Doubles (Just like in
Replace the DOCs by Test Doubles (Just like in
movie industry)
• Test Doubles will provide the same API used
Test Doubles will provide the same API used
by SUT
• SUT ill
SUT will use the Test Double without knowing
h T D bl i h k i
it’s a “Imposter”
João Pereira, Sep. 2011 58
60. Test Doubles
• Test Doubles can take many forms depending
Test Doubles can take many forms, depending
on the purpose:
– Dummy Objects
Dummy Objects
– Fakes
– Stubs
– Spies
–M k
Mocks
João Pereira, Sep. 2011 60
61. Test Doubles
• Test Doubles can take many forms, depending on the
Test Doubles can take many forms, depending on the
purpose:
–Dummy Objects
Dummy Objects
– Fakes
– Stubs
– Spies
– Mocks
João Pereira, Sep. 2011 61
62. Test Doubles: Dummy Objects
• Problem: An SUT method signature requires
Problem: An SUT method signature requires
and object as a parameter, however we don’t
care about what the value of the object is.
• Ex: public class ClassUnderTest {
public boolean openDoor(DoorRequest doorRequest) {
//Code goes here
}
}
public class TestClassUnderTest {
public void testDorShouldNotOpen() {
// Dummy doorRequest.
DoorRequest doorRequest = new DoorRequest();
ClassUnderTest sut = new ClassUnderTest();
assert !sut.openDoor(doorRequest) : "The door shouldn't open";
}
}
João Pereira, Sep. 2011 62
63. Test Doubles: Dummy Objects
• Dummy Objects generally appear in the form
Dummy Objects, generally, appear in the form
of:
– Literal Value
Literal Value
– Derived Value
– Generated Value
Generated Value
João Pereira, Sep. 2011 63
64. Test Doubles: Dummy Objects
• A Literal Value is any value we use for
A Literal Value is any value we use for
attributes of Objects in our test fixtures.
• Ex:
public void testDoorShouldOpen() {
String doorIdLiteralValue = "AHBV834";
// Dummy doorRequest
doorRequest.
DoorRequest doorRequest = new DoorRequest();
//Using the literal value for populating the dummy doorRequest object
doorRequest.setDoorId(doorIdLiteralValue);
DoorManager sut = new DoorManager();
//Exercise SUT
sut.closeDoor(doorRequest);
//Verify using the literal value
assert !sut.getDoor(doorIdLiteralValue).isOpen(): "The door should be closed!";
}
João Pereira, Sep. 2011 64
65. Test Doubles: Dummy Objects
• A Derived Value, also know as Calculated Value,
e ed a ue, a so o as Ca cu ated a ue,
is any value calculated from other values
• Ex:
public void testDoorCodeShouldBeSet() {
String doorIdLiteralValue = "AHBV834";
Door dummyDoor = new Door();
//Calculated code from the algorithm in Door and some literal value
String doorCode = dummyDoor.generateCode("142536A");
DoorRequest doorRequest = new DoorRequest();
// Using the literal value for creating the dummy doorRequest object
doorRequest.setDoorId(doorIdLiteralValue);
//Use the derived value
doorRequest.setCode(doorCode);
d R t tC d (d C d )
DoorManager sut = new DoorManager();
// Exercise
sut.openDoor(doorRequest);
// Verify using the literal value
assert sut.getDoor(doorIdLiteralValue).isOpen() : "The door should be closed! ;
The closed!";
}
João Pereira, Sep. 2011 65
66. Test Doubles: Dummy Objects
• A Generated Value, is a value that is
A Generated Value, is a value that is
generated each time a test runs.
• Ex:
public void testCreateDoor() {
// Create a randomly generated BigInteger, uniformly distributed over
// the range 0 to 2^130 -1, then convert it to a string using a radix of
2 130 1,
// 32
String doorCode = new BigInteger(130, new SecureRandom()).toString(32);
Door door = new Door();
door.setCode(doorCode);
//Rest of the test
}
João Pereira, Sep. 2011 66
67. Test Doubles
• Test Doubles can take many forms, depending on the
Test Doubles can take many forms, depending on the
purpose:
– Dummy Objects
–Fakes
– Stubs
– Spies
– Mocks
João Pereira, Sep. 2011 67
68. Test Doubles: Fakes
• Problem: An SUT’s DOC is not available or is
Problem: An SUT s DOC is not available or is
not suitable for using in tests.
• Ex:
X
João Pereira, Sep. 2011 68
69. Test Doubles: Fakes
• A Fake Object is a more simpler lightweight
A Fake Object is a more simpler, lightweight
object than the real DOC
• Ex:
public void testCloseDoor() {
Door sut = new Door(new FakeController());
assert sut.close(): "The door should be closed ;
The closed";
}
While the USBDoorController may use
your USB drivers, the FakeController may
simple use some simulator, for example.
i l i l t f l
João Pereira, Sep. 2011 69
70. Test Doubles: Fakes
• Common uses of Fakes:
Co o uses o a es:
– Fake Database offers same functionality as the real
db, but is more lightweight. Example: Use HashMaps
or In‐Memory Databases (ex: HSQL In Memory DB)
I M D t b ( HSQL I M DB)
– Fake Webservice Instead of using the real web
service, use one with the same API but that returns
,
fake data
– Fake Service Layer For GUI coding, the service layer
API can be implemented to return fake data to the
API b i l t dt t f k d t t th
Presentation Layer
João Pereira, Sep. 2011 70
71. Test Doubles
• Test Doubles can take many forms, depending on the
Test Doubles can take many forms, depending on the
purpose:
– Dummy Objects
– Fakes
–Stubs
– Spies
– Mocks
João Pereira, Sep. 2011 71
72. Test Doubles: Stubs
• Problem: An SUT’s DOC is not available, or is
Problem: An SUT s DOC is not available, or is
not suitable for using in tests, but you need
indirect input from the DOC to SUT.
• Ex:
Input from DOC
f
is needed!
João Pereira, Sep. 2011 72
73. Test Doubles: Stubs
• Problem: An SUT’s DOC is not available, or is
Problem: An SUT s DOC is not available, or is
not suitable for using in tests, but you need
indirect input from the DOC to SUT.
• Ex:
Input from DOC
f
is simulated!
João Pereira, Sep. 2011 73
74. Test Doubles
• Test Doubles can take many forms, depending on the
Test Doubles can take many forms, depending on the
purpose:
– Dummy Objects
– Fakes
– Stubs
Spies
–Spies
– Mocks
João Pereira, Sep. 2011 74
75. Test Doubles: Spies
• Problem: An SUT’s DOC is not available, or is
Problem: An SUT s DOC is not available, or is
not suitable for using in tests, but DOC’s
output, or behavior, is required to be verified.
• Ex:
Output/behavior from
p /
DOC is required to be
verified!
João Pereira, Sep. 2011 75
76. Test Doubles: Spies
• Problem: An SUT’s DOC is not available or is not
Problem: An SUT s DOC is not available, or is not
suitable for using in tests, but DOC’s output, or
behavior, is required needed to be verified.
, q
• Ex:
Output/behavior from DOC
is recorded and can be
verified afterwards
João Pereira, Sep. 2011 76
77. Test Doubles: Spies
• Example: We don’t really want to send an
Example: We don t really want to send an
email, but we want to know if the email was
sent when method doorsInDanger is
sent when method doorsInDanger is
executed.
João Pereira, Sep. 2011 77
78. Test Doubles: Spies
• Example: We don’t really want to send an
Example: We don t really want to send an
email, but we want to know if the email was
sent when method doorsInDanger is
sent when method doorsInDanger is
executed.
Output/behavior from DOC
is recorded and can be
verified afterwards
João Pereira, Sep. 2011 78
79. Test Doubles: Spies
• In Java:
In Java:
MailService.java
public interface MailService {
public void sentEmail(String email);
}
DoorManager.java
p
public class DoorManager {
g
private MailService mailService;
public void setMailService(MailService mailService) {
this.mailService = mailService;
}
public void doorsInDanger() {
// Some l i
logic
mailService.sentEmail("Contents...");
}
}
João Pereira, Sep. 2011 79
80. Test Doubles: Spies
• In Java:
In Java:
TestMailService.java
public class TestMailService implements MailService {
// Store the sent emails
private List<String> sentEmails = new ArrayList<String>();
/**
* Get the number of mails sent since initialization
*
* @return The number of emails sen
*/
public int getNumberOfSentEmails() {
return sentEmails.size();
}
@Override
public void sentEmail(String email) {
// Will not send the email. Just record it
this.sentEmails.add(email);
}
}
João Pereira, Sep. 2011 80
81. Test Doubles: Spies
• In Java:
In Java:
DoorManagerTest.java
public class DoorManagerTest {
public void sendNotificationToOwner() {
MailService spyMail = new TestMailService();
DoorManager sut = new DoorManager();
sut.setMailService(spyMail);
// doorsInDanger logs the incident in LOG and sent an email to the owner
// of the Door
sut.doorsInDanger();
assert ((TestMailService)spyMail).getNumberOfSentEmails()==1: "Should have sent one
email";
}
}
João Pereira, Sep. 2011 81
82. Test Doubles
• Test Doubles can take many forms, depending on the
Test Doubles can take many forms, depending on the
purpose:
– Dummy Objects
– Fakes
– Stubs
– Spies
p
–Mocks
João Pereira, Sep. 2011 82
83. Test Doubles: Mocks
• Problem: An SUT’s DOC is not available, or is not
,
suitable for using in tests, but DOC’s calls, in a
defined order, are expected to occurs in order to
verify SUT behavior.
verify SUT behavior
• Ex:
Is expected that SUT calls
DOC in this order.
DOC i thi d
João Pereira, Sep. 2011 83
84. Test Doubles: Mocks
• Problem: An SUT’s DOC is not available, or is not
,
suitable for using in tests, but DOC’s calls, in a
defined order, are expected to occurs in order to
verify SUT behavior.
verify SUT behavior
• Ex:
João Pereira, Sep. 2011 84
87. What is Mockito?
• “Mockito is a mocking framework that tastes
Mockito is a mocking framework that tastes
really good. It lets you write beautiful tests
with clean & simple API. Mockito doesn t give
with clean & simple API Mockito doesn’t give
you hangover because the tests are very
readable and they produce clean verification
readable and they produce clean verification
errors” – http://code.google.com/p/mockito
João Pereira, Sep. 2011 87
88. What can Mockito do for you?
• Helps you develop test easily using Mocks
Helps you develop test easily using Mocks
• Provides a framework for creating and using
Stubs
• Allows you to follow BDD (Behavior driven
Development) technique
D l ) h i
João Pereira, Sep. 2011 88
89. A first example using Mocks
• Let’s consider the following class diagram:
Let s consider the following class diagram:
A DoorService is the API used to manage
DoorUnits. Most of the operations on
DoorService are delegated to a
DoorUnitManager i t
D U itM instance.
João Pereira, Sep. 2011 89
90. A first example using Mocks
Let s create a test for the
Let’s create a test for the
DoorService. The first
method we will implement is
h d ill i l i
addDoorUnit.
João Pereira, Sep. 2011 90
91. A first example using Mocks
• A first draft of the unit test for
A first draft of the unit test for
addDoorUnit:
@Test
public void testAddDoorUnit() {
//Need a service. Our SUT
DoorService sut = createTestDoorService(null);
DoorUnit d
i dummyDoorUnit = createDummyDoorUnit();
i i ()
sut.addDoorUnit(dummyDoorUnit);
}
How should we really test?
João Pereira, Sep. 2011 91
92. A first example using Mocks
Back to our first design; we said that most
ope a o s o a oo Se
operations on a DoorService are to be
ce a e o be
delegated to DoorUnitManager
instance.
In those cases we only want to be sure that
the appropriate methods are called on a
DoorUnitManager.
D U itM
João Pereira, Sep. 2011 92
93. A first example using Mocks
• Complete unit test for addDoorUnit
Complete unit test for addDoorUnit
@Test
public void testAddDoorUnit() {
DoorUnitManager mockedDoorUnitManager = mock(DoorUnitManager.class);
//Need a service. Our SUT
DoorService sur = createTestDoorService(mockedDoorUnitManager);
DoorUnit dummyDoorUnit = createDummyDoorUnit();
//exercise
sur.createDoorUnit(dummyDoorUnit);
//Verify expectations on the mockedDoorUnitManager
verify(mockedDoorUnitManager).addDoorUnit(dummyDoorUnit);
verify(mockedDoorUnitManager) addDoorUnit(dummyDoorUnit);
}
João Pereira, Sep. 2011 93
94. A first example using Stubs
• Next let’s implement findDoorUnit
Next, let s implement findDoorUnit
method
João Pereira, Sep. 2011 94
95. A first example using Stubs
• A first draft of the unit test for
A first draft of the unit test for
findDoorUnit:
@Test
public void testFindDoorUnit() {
DoorUnitManager mockedDoorUnitManager = mock(DoorUnitManager.class);
// Need a service Our SUT
service.
DoorService sut = createTestDoorService(mockedDoorUnitManager);
DoorUnit dummyDoorUnit = createDummyDoorUnit();
// Let's first add it
sut.addDoorUnit(dummyDoorUnit);
// Now find it by name
DoorUnit foundDoorUnit = sut.findDoorUnit(dummyDoorUnit.getName());
FAIL!! assertEquals(dummyDoorUnit, foundDoorUnit);
}
João Pereira, Sep. 2011 95
96. A first example using Stubs
• Complete unit test for findDoorUnit:
Complete unit test for findDoorUnit:
@Test
public void testFindDoorUnit() {
// Our mocked DOC
DoorUnitManager mockedDoorUnitManager = mock(DoorUnitManager.class);
// Need a service. Our SUT
DoorService sut = createTestDoorService(mockedDoorUnitManager);
DoorUnit dummyDoorUnit = createDummyDoorUnit();
// L t' fi t add it
Let's first dd
sut.addDoorUnit(dummyDoorUnit);
// stubbing what is expected from DOC
when(mockedDoorUnitManager.findByName(dummyDoorUnit.getName()))
.thenReturn(dummyDoorUnit);
y
// Now find it by name
DoorUnit foundDoorUnit = sut.findDoorUnit(dummyDoorUnit.getName());
assertEquals(dummyDoorUnit, foundDoorUnit);
}
João Pereira, Sep. 2011 96
97. Want to learn more?
• http://code google com/p/mockito/
http://code.google.com/p/mockito/
• http://docs.mockito.googlecode.com/hg/lates
t/org/mockito/Mockito.html
t/org/mockito/Mockito html
• http://docs.mockito.googlecode.com/hg/lates
t/org/mockito/BDDMockito.html
/ / ki /BDDM ki h l
João Pereira, Sep. 2011 97
99. Other alternatives
These can be combined to suit
your needs. They can even be
your needs They can even be
enriched with scripting
jmockit
languages!!!
João Pereira, Sep. 2011 99
100. Programmer testing
• What is a Test?
• Overview of Agile testing quadrants
• What is Test Driven Development
• Overview of unit testing and JUnit
• Introduction to Test Doubles and Mockito
• Measure code coverage with Cobertura
• Exercises
• References
João Pereira, Sep. 2011 100
101. What is code coverage?
What is
Wh t i Code Coverage ?
C d C
João Pereira, Sep. 2011 101
102. What is code coverage?
• A measure that indicates the degree to which
A measure that indicates the degree to which
a program has been tested.
– Consider the following java method:
Consider the following java method:
public int foo(int a, int b) {
int result = -1;
if (a > 0 && b > 0) {
result = a / b;
}
if ( <= 0 || b < 0) {
(a < <=
result = -1;
}
return result;
}
João Pereira, Sep. 2011 102
103. What is code coverage?
• …and consider this test:
and consider this test:
@Test
public void testFoo() {
SystemUnderTest sut = new SimpleDoorServiceTest();
assertEquals( 1, sut.foo( 2,
assertEquals(-1 sut foo(-2 3));
}
João Pereira, Sep. 2011 103
104. What is code coverage?
How good this test…
@Test
public void testFoo() {
SystemUnderTest sut = new SimpleDoorServiceTest();
assertEquals(-1, sut.foo(-2, 3));
}
…cover all statements in this code?
public int foo(int a, int b) {
int result = -1;
if (a > 0 && b > 0) {
result = a / b;
}
if (a <= 0 || b <= 0) {
result = -1;
}
return result;
}
João Pereira, Sep. 2011 104
105. What is code coverage?
Line Coverage Branch Coverage
g Branch Coverage
Number of hits
João Pereira, Sep. 2011 105
106. What is code coverage?
• Number of hits How many times the
Number of hits How many times the
statement was executed during the tests?
• Line coverage What is the percentage of
Line coverage What is the percentage of
the total number of lines of code that are
being tested?
• Branch coverage What is the percentage of
the total branches that are being tested?
• Complexity What is the Average McCabe's
cyclomatic code complexity?
João Pereira, Sep. 2011 106
107. What is code coverage?
• Branch coverage:
Branch coverage:
Tested values
Tested values
A B Branch Cumulative Branch coverage
Coverage
>0
0 >0
0 25% 25%
>0 <0 25% 50%
<0 >0 25% 75%
<0
0 <0
0 25%
100%
João Pereira, Sep. 2011 107
108. What is code coverage?
100% Coverage is not good enough to tell
Tested values
Tested values g
A that our software is bug free. It just tell us that
B Branch Cumulative Branch coverage
tests are executing all statements and branches
Coverage
>0
0 >0
0 25% 25%
of our code. It doesn’t tell, however, that we’re
f d I ll h h ’
>0 <0 25% 50%
making the correct assumptions, or that we fully
<0 >0 25% 75%
understand the problem!!.
p
<0
0 <0
0 25%
100%
João Pereira, Sep. 2011 108
109. What is code coverage?
• Complexity (number of decision points (if else for while
Complexity (number of decision points (if, else, for. while,
case) + 1
public int foo(int a, int b) {
int result = -1;
1 1
if (a > 0 && b > 0) {
result = a / b;
} 1 1
if (a <= 0 || b <= 0) {
result = -1;
}
return result;
} Complexity: 5
João Pereira, Sep. 2011 109
110. What is code coverage?
• Equivalent to:
Equivalent to:
public int fooMethod(int a, int b) {
int result = -1;
if (a > 0) { 1
if (b > 0) { 1
result = a / b;
}
}
if (a <= 0) { 1
result = -1;
}
if (b <= 0) {
result = -1; 1
;
}
return result;
}
Complexity: 5
João Pereira, Sep. 2011 110
111. What is code coverage?
Tested values
Tested values
Code with high* complexity can be a pain
A B Branch Cumulative Branch coverage
Coverage
for maintenance and it increases the
>0
0 >0
0 25% 25%
probability of bugs.
b bilit f b
>0 <0 25% 50%
*An generally accepted higher limit is 10
<0 >0 25% 75%
<0
0 <0
0 25%
100%
João Pereira, Sep. 2011 111
112. Cobertura
• Better integrated with Maven Just run:
Better integrated with Maven. Just run:
mvn cobertura:cobertura
• Know more about Cobertura:
– http://cobertura.sourceforge.net/
• Know more about Maven Cobertura Plugin:
g
– http://mojo.codehaus.org/cobertura‐maven‐
p g /
plugin/
João Pereira, Sep. 2011 112
114. Programmer testing
• What is a Test?
• Overview of Agile testing quadrants
• What is Test Driven Development
• Overview of unit testing and JUnit
• Introduction to Test Doubles and Mockito
• Measure code coverage with Cobertura
• References
João Pereira, Sep. 2011 114
115. Programmer testing
• What is a Test?
• Overview of Agile testing quadrants
• What is Test Driven Development
• Overview of unit testing and JUnit
• Introduction to Test Doubles and Mockito
• Measure code coverage with Cobertura
• References
João Pereira, Sep. 2011 115
116. References about Testing subjects
• Books:
– The Art of Software Testing, Second Edition
• http://amzn to/art‐of‐software‐testing
http://amzn.to/art‐of‐software‐testing
– Agile Testing: A Practical Guide for Testers and
Agile Teams
Agile Teams
• http://amzn.to/agile‐testing
– Code Complete 2: A Practical Handbook of
p
Software Construction
• http://amzn.to/code‐complete
João Pereira, Sep. 2011 116