Hamcrest is a library for creating matchers for usage in unit tests, mocks and UI validation. This talk gives a brief introduction to using and writing Hamcrest matchers.
The topics covered:
* Basic introduction to Hamcrest
* Using Matchers in assertions
* Using Matchers with Mockito
* Writing custom matchers
* Ad-hoc matchers
SQLLite and Java
SQLite is an embedded SQL database that is not a client/server system but is instead accessed via function calls from an application. It uses a single cross-platform database file. The android.database.sqlite package provides classes for managing SQLite databases in Android applications, including methods for creating, opening, inserting, updating, deleting, and querying the database. Queries return results as a Cursor object that can be used to access data.
This document provides an overview of Selenium WebDriver for test automation. It discusses what WebDriver is, its features for controlling browsers, and how it interacts with the Document Object Model (DOM). Locators for finding elements in the DOM are described. An example test task is presented for logging into a web application. The Page Object pattern is introduced as a best practice for organizing WebDriver tests. Code snippets demonstrate low-level WebDriver methods and handling pop-up windows.
This document provides an overview and introduction to testing Android apps with Espresso:
- Espresso is a testing framework created by Google for writing reliable UI tests for Android apps. It allows writing tests to interact with views in the app and check their expected behavior.
- The core components of Espresso include matchers to find views, actions to perform interactions, and assertions to validate views match expected states. Common matchers, actions, and assertions are introduced.
- Configuration and setup for Espresso tests in Android projects is explained, including dependencies, test rules, and JUnit annotations. Additional libraries that extend Espresso functionality are also listed.
This document provides an introduction to unit testing and mocking. It discusses the benefits of unit testing such as safer refactoring and value that increases over time. It provides a recipe for setting up a unit test project with test classes and methods using AAA syntax. It also covers what mocking is and how to use mocking frameworks to create fake dependencies and check interactions. Resources for learning more about unit testing and related tools are provided.
The document provides an overview of the traditional UI development approach and introduces the Model-View-ViewModel (MVVM) architectural pattern. It defines the key components of MVVM - the Model, View, and ViewModel - and describes how they interact through data binding, commands, and notifications. The summary highlights MVVM's separation of concerns, support for independent development and testing of components, and facilitation of UI redevelopment.
This document provides an overview of SwiftUI, Apple's declarative UI framework. It begins by discussing declarative programming and how SwiftUI uses this paradigm through property wrappers and the @ViewBuilder attribute. Next, it demonstrates SwiftUI concepts like modifiers, data binding, and state management. It then covers interfacing SwiftUI and UIKit, including the UIHostingController and UIViewRepresentable protocols. Finally, it discusses Swift language features that support SwiftUI's declarative model like implicit returns and opaque return types.
Slides from the NestJS MasterClass.
We learned how to build JavaScript server-side applications with NestJS - A progressive NodeJS framework built with TypeScript.
You can find the code on GitHub:
https://github.com/nirkaufman/task-manager
Introduction to the Spring Framework:
Generar description
IoC container
Dependency Injection
Beans scope and lifecycle
Autowiring
XML and annotation based configuration
Additional features
TestNG is a testing framework that supports unit testing, integration testing, annotations, parameters, listeners, test groups, and dependencies. It allows specifying before and after methods, data providers, and test run configuration via XML. Key features include annotations for configuring tests, parameters to pass data to tests, listeners to customize test runs, and groups and dependencies to control test order and relationships. TestNG can be run from the command line, Ant, Eclipse, IntelliJ, and is supported in Maven and Ant builds.
The document discusses several core Java concepts including:
1) Comments in Java code can be single-line or multiline javadoc comments.
2) Classes are fundamental in Java and describe data objects and methods that can be applied to objects.
3) Variables and methods have scopes determined by curly braces and a variable is only available within its scope.
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 Spring Boot and some of its key features. It discusses the origins and modules of Spring, how Spring Boot simplifies configuration and dependency management. It then covers examples of building Spring Boot applications that connect to a SQL database, use RabbitMQ for messaging, and schedule and run asynchronous tasks.
Selenium is a tool for automating web application testing that allows tests to be written in various programming languages; it has multiple components including Selenium IDE for recording and playback of tests in Firefox, and Selenium RC which allows tests to be run from external languages and provides more power and flexibility than the IDE. Tests can be used to check for correct behavior and responses across different browsers and platforms as well as catch regressions.
This document provides an overview of a Selenium training course. The course is divided into modules covering Selenium User, Practitioner, and Expert topics. The Selenium User module focuses on the basics of Selenium and using the Selenium IDE. It includes exercises for locating elements and writing simple test scripts. The document also provides references and demo websites for practicing Selenium.
Java Server Faces (JSF) is a component-based MVC framework for building user interfaces in Java web applications. JSF provides UI components that can be used in JSP or Facelets views. It follows a request response lifecycle where the controller handles gathering input, validating, updating models, and rendering responses. Popular JSF components include inputs, outputs, selects, forms, and commands. Facelets is the default view technology in JSF 2 and provides templating capabilities. Key differences between JSF and JSF 2 include replacing JSP with Facelets and adding Ajax and annotation support. Spring MVC has the highest demand and documentation quality while Struts 2 has the lowest learning curve and JSF is in
The document provides an overview and agenda for a presentation on SwiftUI. The presentation covers declarative programming with SwiftUI, compares SwiftUI and UIKit, demonstrates navigation, data binding, and integrating SwiftUI and UIKit. It also discusses SwiftUI concepts like modifiers, previews, and requirements to use SwiftUI. The presentation aims to provide a deep dive into SwiftUI fundamentals and capabilities.
JUnit is the de facto standard in Java testing. Yet many advanced JUnit features are little known and poorly understood. This session reviews some lesser-known features of JUnit, along with a few associated libraries, that can make your unit tests more powerful, expressive, and fun. The session is intended for Java developers, lead developers, and architects trying to introduce good testing practices into their teams.
Xavi Rigau presented on UI testing with Espresso. Espresso is an Android UI testing framework that allows writing easy to set up, fluid, and fast UI tests. It has a high-level API based on matchers that makes tests readable. Espresso tests are extensible through custom matchers and do not require calls to sleep due to its smart waiting functionality. The presentation demonstrated the Espresso API and encouraged attending to try out writing sample tests on their own.
The document discusses how test-driven development (TDD) can help software developers avoid design mistakes that stem from relying too heavily on past experience. It notes that experience can make developers vulnerable by leading them to automatically apply familiar patterns without considering if they are the best solution. TDD encourages an incremental "beginner's mind" approach where the simplest code is written to pass each test before refactoring, which helps developers introduce the right abstractions and avoid over-engineering. Refactoring is key to improving designs emerging from TDD. The document advocates practicing TDD and refactoring to cultivate humility and flexibility in design.
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.
Quality assurance and testing are very important in a life cycle of any application. Although, by far not all developers understand the significance of tests.
In this presentation, we cover the basic testing practices for developers. The following tools are discussed: JUnit, Mockito, Hamcrest, JsTestDriver, DBUnit, Arquillian, SoapUI, Selenium.
Reliable tests with selenium web driverPawelPabich
Reliable end-to-end (e2e) tests are important for assuring code quality and encouraging refactoring, but unreliable e2e tests are harmful. To write reliable e2e tests, focus on the happy path, test only code you own, navigate directly to the screen under test, and make sure the system is in a known initial state. Avoid using Thread.Sleep and test recorders, and test only one scenario at a time.
Palestra apresentando os primeiros passos na utilização do JUnit, Espresso e UIAutomator para a automação de testes em Apps Android, além de como utilizar os testes criados em uma device farm na nuvem para execução dos testes.
Para vídeos sobre o funcionamento do TestDroid verifique o canal deles no YouTube: https://www.youtube.com/user/BitbarChannel
"Design and Test First"-Workflow für REST APIsMarkus Decke
Often we as developers hand craft REST APIs, that can be cumbersome.
Requirements shouldn't be copied to code, either for tests or production.
In my talk I want to stress that we can have a better workflow with REST API specification projects, than the usual one.
I held this at bedon conference 2015 http://bed-con.org/2015/
AssertJ-core is a Java library that provides a fluent interface for writing assertions. It can be installed using Maven and provides examples of how to write basic assertions like checking for expected exceptions and comparing arrays. AssertJ-core allows assertions to be written in a fluent style and is concluded to be the best assertion library for Java.
This talk is based on heated discussions about the syntax of asserts. Do you like the good old `assertNotEquals(id, c.getId())` or do you prefer something fancier like `assertThat(id, is(not(equalTo(c.getId()))))`?
We will take a quick look at the differences between asserts in JUnit, TestNG, Hamcrest, fest, AssertJ, and Spock. This topic is at least as important as Vim vs Emacs and tabs vs spaces!
Topic: Software engineering practices
Language: English
The document introduces property-based testing, which generates random input values to test code in multiple scenarios, unlike example-based testing which uses a single example. It discusses how JUnit, Junit-Quickcheck, and Quicktheory support property-based testing in Java with features like random data generation, assumptions to filter values, seeding to reproduce tests, and shrinking to minimize failing tests. The goal is to present an overview of property-based testing and compare the main Java libraries that support it.
Illia Seleznov - Integration tests for Spring Boot applicationAnna Shymchenko
This document discusses integration testing for Spring Boot applications. It covers testing levels from unit to system level and the importance of automation. It then discusses why Spring Boot is useful for testing and provides examples of testing DAOs, transactions and exception handling. Various testing approaches like embedded server, database and domain models are presented. It also touches on common problems like tests not being independent and slow tests. Solutions provided include avoiding changing common data, rebuilding database after each test and using MockMVC.
Espresso is a testing framework for Android that makes it easy to write reliable UI tests. It was developed by Google and released in 2013. The document discusses what Espresso is, similar automation frameworks, advantages of Espresso, and how to set it up and write tests using its API. Key aspects of the API are finding views with matchers, interacting with views using actions, and asserting view states with matchers.
The document discusses various testing techniques including parameterized tests. It provides an example of using parameterized tests with JUnit 4.8.1 to test a tax calculator with sample income and expected tax data. The test class is annotated with @RunWith(Parameterized.class) and has fields for the income and expected tax. It constructs test instances with the data and includes a test that verifies the calculated tax matches the expected value.
This document discusses various techniques for unit testing in Java with JUnit, including naming tests clearly, using Hamcrest matchers for assertions, writing parameterized tests, using JUnit rules, and measuring code coverage. It provides examples of how to write tests that follow best practices and leverage JUnit's capabilities for parameterized testing, timeouts, error collection, and more. It also discusses running tests in parallel and measuring code coverage in IDEs like IntelliJ and Eclipse.
This document discusses client-server connections for a library application. It provides code for a CustomHttpClient class that defines methods for performing HTTP GET and POST requests. This includes setting connection timeout parameters. It also provides code for connecting to a MySQL database and inserting login credentials and book borrowing history. The code samples show how to connect between the client and server and interface with the backend database.
The document provides steps for creating a TodoList application using Swift and Kitura including:
- Creating a project and adding dependencies
- Setting up simple routing and error handling
- Using promises and asynchronous callbacks
- Adding a database to store tasks
- Implementing testing with expectations
Swift 5.1 brought a new construct to the language: Property Wrappers. SwiftUI, for instance, relies heavily on it to provide its system of data-binding through annotations like @State, @EnvironmentObjects, etc.
Unlike other language improvements, Codable for instance, Apple hasn’t restricted the use of this new feature to its own frameworks: any codebase is free to leverage it to implement custom property attributes that will suit its own specific needs.
While this is a great opportunity to factorise common behaviours throughout a project, one can still wonder: won’t it hurt code readability and predictability on the long run? Keeping code short is good, but if it’s achieved through a collection of arcane annotations, it might end up defying the original intent.
In this talk, I want to introduce what Property Wrappers are, give some example of how they can be leveraged, and try to provide some guidelines on when we they should or shouldn’t be use.
The document discusses clean coding practices for Java developers. It covers topics such as choosing meaningful names for variables, methods, and classes; writing code that is easy for others to understand; breaking methods down into single logical steps; and using fluent APIs to make code more readable. The presentation provides examples of clean code and ways to refactor code to follow best practices.
Rhino Mocks is a .NET mocking framework that allows developers to easily create and setup mock objects to test interactions using unit tests. It generates both mocks, which allow expectations to be set and verified, and stubs, which simply return preset values without verification. The document provides examples of using Rhino Mocks to generate mocks and stubs of interfaces, set expectations on mocks, and verify mock interactions using the AAA (Arrange, Act, Assert) syntax. It also distinguishes between mocks and stubs.
This document summarizes a test for an ExchangeRateUploader class that uploads exchange rates to a database. The test mocks several dependencies, sets up test data including currencies and exchange rates, and verifies the uploader saves the rates and finalizes the thread.
This document contains code for a registration form validation using regular expressions in JavaScript. The form validation code uses regular expressions to validate the name, email, phone number, and other fields. When the form is submitted, the validation functions tests the values against the regular expressions and displays alerts for any invalid fields.
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."sjabs
The document discusses Hadoop and its applications. It provides examples of companies like Facebook and their use of Hadoop. It also discusses Hadoop components like HDFS, MapReduce, Pig and HBase. It provides examples of using Hadoop with databases like MongoDB and search engines like Solr. It notes that not every problem requires large-scale solutions and discusses potential use cases for Hadoop including log analysis, indexing documents and building recommendation systems.
Java has a reputation for boilerplate code: ubiquitous getters and setters, a verbose anonymous class syntax, and redundant declarations to name a few. It doesn't have to be this way! There are many ways to bust the boilerplate and this session provides a solid understanding of the most modern techniques. Come learn about inversion of control idioms, Proxy objects, code generation tools, and the latest libraries that both create and manage boilerplate code so you don't have to. A leaner, meaner codebase is yours for the taking.
The talk presents how we established a TDD cycle within the complex AEM technology stack using a "unified testing API". It illustrates how such an API can be built and discusses various advantages over other approaches such as the Sling Testing API.
This document provides an overview and examples of using Google Guava, an open-source Java library that includes common libraries useful for writing Java code. It highlights some key classes and methods in Guava, including annotations, strings, collections, I/O, and more. Code samples demonstrate using Guava features like predicates, sets, files, and InetAddress utilities.
Redis is an in-memory data structure store that can be used as a database, cache, or message broker. It supports basic data structures like strings, hashes, lists, sets, sorted sets with ranges, and bitmaps. The Spring Data Redis library makes it easy to use Redis from Spring applications to store and retrieve objects and leverage features like pub/sub and caching.
The document discusses various techniques for reducing boilerplate code in Java, including libraries like Google Guava, Apache Commons Lang, and features in Java 7 and later. It provides examples of using these libraries and features to simplify tasks like error handling, resource management, string processing, collections, and object representation.
The document discusses various options for querying data with Hibernate including:
1) The Hibernate Query Language (HQL) and Criteria API for defining type-safe queries against objects rather than tables.
2) Techniques for executing queries such as pagination, scrolling results, and binding parameters.
3) Advanced query features like joining associations, aggregation, grouping, and report queries for projecting specific fields.
The document provides information about a JavaScript course including:
1. The course consists of 5 lectures and 5 labs and is evaluated based on projects, assignments, labs and quizzes.
2. The lecture outline covers introduction to JavaScript, syntax, built-in objects and functions.
3. JavaScript was invented by Brendan Eich at Netscape and first appeared in the Netscape Navigator browser in 1995.
This document discusses improving the Java type system by adding behavioral assertions. It describes how assertions can be added for fields, methods, constructors, and on method entry/exit. Fields are handled by injecting code to track writes. Method assertions are added by wrapping the original method. Constructor assertions are added by inserting code before the body. Entry/exit assertions require injecting code at both the start and end of the method. The approach aims to not break original program functionality while checking assertions. Examples are provided for each case.
This document provides an overview of Java SCORE on ICON. It discusses why Java and the JVM were chosen, how bytecode is instrumented to work with ICON, the structure and APIs of Java SCORE compared to Python SCORE, and storage models including object graphs and key-value stores. It also covers error handling, supporting return types and collections, and object serialization in databases.
Similar to Writing and using Hamcrest Matchers (20)
Using ScyllaDB for Real-Time Write-Heavy WorkloadsScyllaDB
Keeping latencies low for highly concurrent, intensive data ingestion
ScyllaDB’s “sweet spot” is workloads over 50K operations per second that require predictably low (e.g., single-digit millisecond) latency. And its unique architecture makes it particularly valuable for the real-time write-heavy workloads such as those commonly found in IoT, logging systems, real-time analytics, and order processing.
Join ScyllaDB technical director Felipe Cardeneti Mendes and principal field engineer, Lubos Kosco to learn about:
- Common challenges that arise with real-time write-heavy workloads
- The tradeoffs teams face and tips for negotiating them
- ScyllaDB architectural elements that support real-time write-heavy workloads
- How your peers are using ScyllaDB with similar workloads
TrustArc Webinar - Innovating with TRUSTe Responsible AI CertificationTrustArc
In a landmark year marked by significant AI advancements, it’s vital to prioritize transparency, accountability, and respect for privacy rights with your AI innovation.
Learn how to navigate the shifting AI landscape with our innovative solution TRUSTe Responsible AI Certification, the first AI certification designed for data protection and privacy. Crafted by a team with 10,000+ privacy certifications issued, this framework integrated industry standards and laws for responsible AI governance.
This webinar will review:
- How compliance can play a role in the development and deployment of AI systems
- How to model trust and transparency across products and services
- How to save time and work smarter in understanding regulatory obligations, including AI
- How to operationalize and deploy AI governance best practices in your organization
Getting Ready for Copilot for Microsoft 365 with Governance Features in Share...Juan Carlos Gonzalez
Session delivered at the Microsoft 365 Chicago Community Days where I introduce how governance controls within SharePoint Premium are a key asset in a succesfull rollout of Copilot for Microsoft 365. The session was mostly a hands on session with multiple demos as you can see in the session recording available in YouTube: https://www.youtube.com/watch?v=MavcP6k5nU8&t=199s. For more information about Governance controls available in SharePoint Premium visit official documentation available at Microsoft Learn: https://learn.microsoft.com/en-us/sharepoint/advanced-management
Selling software today doesn’t look anything like it did a few years ago. Especially software that runs inside a customer environment. Dreamfactory has used Anchore and Ask Sage to achieve compliance in a record time. Reducing attack surface to keep vulnerability counts low, and configuring automation to meet those compliance requirements. After achieving compliance, they are keeping up to date with Anchore Enterprise in their CI/CD pipelines.
The CEO of Ask Sage, Nic Chaillan, the CEO of Dreamfactory Terence Bennet, and Anchore’s VP of Security Josh Bressers are going to discuss these hard problems.
In this webinar we will cover:
- The standards Dreamfactory decided to use for their compliance efforts
- How Dreamfactory used Ask Sage to collect and write up their evidence
- How Dreamfactory used Anchore Enterprise to help achieve their compliance needs
- How Dreamfactory is using automation to stay in compliance continuously
- How reducing attack surface can lower vulnerability findings
- How you can apply these principles in your own environment
When you do security right, they won’t know you’ve done anything at all!
Discovery Series - Zero to Hero - Task Mining Session 1DianaGray10
This session is focused on providing you with an introduction to task mining. We will go over different types of task mining and provide you with a real-world demo on each type of task mining in detail.
Project Delivery Methodology on a page with activities, deliverablesCLIVE MINCHIN
I've not found a 1 pager like this anywhere so I created it based on my experiences. This 1 pager details a waterfall style project methodology with defined phases, activities, deliverables, assumptions. There's nothing in here that conflicts with commonsense.
DefCamp_2016_Chemerkin_Yury-publish.pdf - Presentation by Yury Chemerkin at DefCamp 2016 discussing mobile app vulnerabilities, data protection issues, and analysis of security levels across different types of mobile applications.
Airports, banks, stock exchanges, and countless other critical operations got thrown into chaos!
In an unprecedented event, a recent CrowdStrike update had caused a global IT meltdown, leading to widespread Blue Screen of Death (BSOD) errors, and crippling 8.5 million Microsoft Windows systems.
What triggered this massive disruption? How did Microsoft step in to provide a lifeline? And what are the next steps for recovery?
Swipe to uncover the full story, including expert insights and recovery steps for those affected.
Webinar: Transforming Substation Automation with Open Source SolutionsDanBrown980551
This webinar will provide an overview of open source software and tooling for digital substation automation in energy systems. The speakers will provide a brief overview of how open source collaborative development works in general, then delve into how it is driving innovation and accelerating the pace of substation automation. Examples of specific open source solutions and real-world implementations by utilities will be discussed. Participants will walk away with a better understanding of the challenges of automating substations, the ecosystem of solutions available to help, and best practices for implementing them.
"Hands-on development experience using wasm Blazor", Furdak Vladyslav.pptxFwdays
I will share my personal experience of full-time development on wasm Blazor
What difficulties our team faced: life hacks with Blazor app routing, whether it is necessary to write JavaScript, which technology stack and architectural patterns we chose
What conclusions we made and what mistakes we committed
Welcome to our third live UiPath Community Day Amsterdam! Come join us for a half-day of networking and UiPath Platform deep-dives, for devs and non-devs alike, in the middle of summer ☀.
📕 Agenda:
12:30 Welcome Coffee/Light Lunch ☕
13:00 Event opening speech
Ebert Knol, Managing Partner, Tacstone Technology
Jonathan Smith, UiPath MVP, RPA Lead, Ciphix
Cristina Vidu, Senior Marketing Manager, UiPath Community EMEA
Dion Mes, Principal Sales Engineer, UiPath
13:15 ASML: RPA as Tactical Automation
Tactical robotic process automation for solving short-term challenges, while establishing standard and re-usable interfaces that fit IT's long-term goals and objectives.
Yannic Suurmeijer, System Architect, ASML
13:30 PostNL: an insight into RPA at PostNL
Showcasing the solutions our automations have provided, the challenges we’ve faced, and the best practices we’ve developed to support our logistics operations.
Leonard Renne, RPA Developer, PostNL
13:45 Break (30')
14:15 Breakout Sessions: Round 1
Modern Document Understanding in the cloud platform: AI-driven UiPath Document Understanding
Mike Bos, Senior Automation Developer, Tacstone Technology
Process Orchestration: scale up and have your Robots work in harmony
Jon Smith, UiPath MVP, RPA Lead, Ciphix
UiPath Integration Service: connect applications, leverage prebuilt connectors, and set up customer connectors
Johans Brink, CTO, MvR digital workforce
15:00 Breakout Sessions: Round 2
Automation, and GenAI: practical use cases for value generation
Thomas Janssen, UiPath MVP, Senior Automation Developer, Automation Heroes
Human in the Loop/Action Center
Dion Mes, Principal Sales Engineer @UiPath
Improving development with coded workflows
Idris Janszen, Technical Consultant, Ilionx
15:45 End remarks
16:00 Community fun games, sharing knowledge, drinks, and bites 🍻
Multimodal Embeddings (continued) - South Bay Meetup SlidesZilliz
Frank Liu will walk through the history of embeddings and how we got to the cool embedding models used today. He'll end with a demo on how multimodal RAG is used.
Self-Healing Test Automation Framework - HealeniumKnoldus Inc.
Revolutionize your test automation with Healenium's self-healing framework. Automate test maintenance, reduce flakes, and increase efficiency. Learn how to build a robust test automation foundation. Discover the power of self-healing tests. Transform your testing experience.
2. What is Hamcrest?
According to the project homepage,
[Hamcrest] provides a library of matcher objects (also known
as constraints or predicates) allowing 'match' rules to be
defined declaratively, to be used in other frameworks. Typical
scenarios include testing frameworks, mocking libraries and
UI validation rules.
Hamcrest is not a testing library: it just happens that
matchers are very useful for testing.
3. Typical usage example
Actual value
assertThat(
someString,
is(equalTo(someOtherString))
);
Expectation on the
value, represented as
a Matcher
4. Wait – but what’s wrong with
assertEquals?
assertEquals(someString, someOtherString)
This looks just as good, doesn’t it?
assertEquals(
cat.getName(),
otherCat.getName())
Not so bad, either
5. However,
What about collections?
assertEquals(someKitten,
cat.getKittens().iterator().next())
This works if our kitten is the first element in the
collection, but what about asserting that the kitten
exists anywhere in the collection?
6. Well, we can do this:
boolean found = false;
for (Kitten kitten : cat.getKittens()) {
if (kitten.equals(someKitten)) found = true;
}
assertTrue(found);
7. But don’t you prefer this?
Iterable<Kitten>
assertThat(
cat.getKittens(),
hasItem(someKitten))
Matcher on
Iterable<Kitten> that
accepts a Matcher<Kitten>
9. Basic Matchers
A Matcher is initialized with the expected
values, which are compared against the
actual object we’re matching against when
invoking the matcher.
10. IsEqual Matcher
class IsEqual<T> extends BaseMatcher<T> {
private final Object object; // c’tor omitted for readability
public boolean matches(Object arg) {
return object.equals(arg);
}
}
11. StringEndsWith Matcher
class StringEndsWith <T> extends BaseMatcher<T> {
private final String suffix; // c’tor omitted for readability
public boolean matches(String s) {
return s.endsWith(suffix);
}
}
13. Mockito in one slide
CatShop catShop = mock(CatShop.class);
when(catShop.purchase(somePurchaseRequest
).thenReturn(someCat) Creating the mock
... do some work Stubbing the mock
verify(catShop) Behavior verification
.purchase(expectedPurchaseRequest)
14. Without Hamcrest
CatPurchase catPurchase = new CatPurchase();
catPurchase.setBreed(“Brittish”);
when(catShop.purchase(catPurchase))
).thenReturn(somePreviouslyStubbedCat)
However, this will force us to set all other fields of the
CatPurchase class, since Mockito will perform an exact match
comparison between our instance and the actual one
15. Of course, you could do this:
when(
catShop.purchase(
any(CatPurchaseDTO.class))
).thenReturn(somePreviouslyStubbedCat)
This works, but lacks the benefit of asserting that our
operation is only valid for the expected input
16. The solution: use argThat()
Mockito helper that creates
an argument matcher from
when( a Hamcrest matcher
catShop.purchase(argThat(
hasPropertyWithValue(
“breed”,
startsWith(“Brittish”))))
).thenReturn(somePreviouslyStubbedCat)
Hamcrest matcher that
accepts a Java Bean
property name and a
nested value matcher
17. Using for behavioral verification
CatDao catDao = mock(CatDao.class);
CatStore catStore = new CatStore (catDao);with a Catcall to
Verify that there was a
CatDao.update() instance,
catStore.saveOrUpdate(existingCat); the ‘name’ property is
for which
“felix” and the ‘kittens’ property is an
verify(catDao).update(argThat( Iterable containing two kittens,
kitten1 and kitten2
allOf(
hasPropertyWithValue(“name”, “felix”),
hasPropertyWithValue(“kittens”,
hasItems(kitten1, kitten2)))));
19. Writing your own matchers
In the previous examples, we used the
hasPropertyWithValue() matcher, which, while
allowing for fluent assertions or stubbing, has
the disadvantage of not being type-safe.
This is where writing custom matchers becomes
useful (or, as some would say, necessary).
21. Dissecting some Wix matchers
class HostMatcher extends TypeSafeMatcher<WixUrl> {
private final Matcher<String> host; // c’tor omitted for readability
public boolean matchesSafely(WixUrl url) {
return host.matches(url.host); Nested matcher that
} will be replayed on the
Actual value being
actual value
matched against
public void describeTo(Description description) {
description.appendText("Host that matches ").appendValue(host); we write a
Here
} readable description of
our expected value
public static HostMatcher hasHost(Matcher<String> host)A utility factory method for
{
return new HostMatcher(host); fluently creating this
} matcher. Not mandatory
} but very convenient.
22. Using our matcher
WixUrl url =
new WixUrl(“http://www.wix.com/some/path”);
assertThat(url, hasHost(is(“www.wix.com”))); ✔
assertThat(url, hasHost(endsWith(“wix.com”))); ✔
assertThat(url, hasHost(is(“google.com”))); ✗
java.lang.AssertionError:
Expected: Host that matches <is ”google.com">
got: <http://www.wix.com/some/path>
23. Another URL matcher
class WixUrlParamMatcher extends TypeSafeMatcher<WixUrl> {
private final Matcher<String> name; // c’tor omitted for readability
url.params is a Map<String, String>, so
private final Matcher<String> value;
we create a matcher for a map entry
around our name and value matchers
public boolean matchesSafely(WixUrl url) { replay it against the actual value
and
return hasEntry(name, value).matches(url.params);
}
public void describeTo(Description description) {
description
.appendText("Param with name ").appendValue(name)
.appendText(" and value ").appendValue(value);
}
}
24. Using the two matchers together
String s = “www.wix.com?p=v1&p=v2&p3=v3”;
WixUrl url = new WixUrl(s);
assertThat(url, allOf(
hasHost(is(“www.wix.com”)),
hasParam(is(“p”), anyOf(is(“v1”), is(“v2”))),
hasParam(is(“p3”), startsWith(“v”))));
25. But wait – my URL is a String!
Sometimes you’ll have matchers that accept a specific
type, such as WixUrl or XML Document. For this
purpose, use a wrapping matcher that performs the
conversion for you:
class StringAsUrlMatcher extends TypeSafeMatcher<String> {
private final Matcher<WixUrl> urlMatcher;
public boolean matchesSafely(String urlString) {
return matcher.matches(new WixUrl(urlString));
}
public void describeTo(Description description) {
description.appendText("Url that matches ")
.appendDescriptionOf(urlMatcher);
}
}
27. Consider the following class
class Proxy {
private final HttpClient httpClient;
private String targetUrl;
public String handle (String path) {
httpClient.execute(// some HttpGet);
}
}
28. The HttpClient interface
public HttpResponse execute(HttpGet get);
Our class under test is expected to replace the domain
in path with targetUrl, thus serving as an HTTP Proxy.
We would like to stub and verify the HttpGet parameter
to make sure it builds the proxy URL properly.
29. My test looks something like this
HttpClient client = mock(HttpClient.class);
String url = “http://www.example.com/”;
{…} handler = new Proxy(client, url);
when(client.execute({www.a.com/path}))
.thenReturn(someResponse);
handler.handle(“www.a.com/path”);
verify(client).execute({www.example.com/path});
30. The solution
Matcher<HttpGet> HttpGet(final Matcher<String> urlMatcher) {
return new TypeSafeMatcher<HttpGet>() {
public boolean matchesSafely(HttpGet httpGet) {
return urlMatcher.matches(httpGet.getURI().toString()));
}
public void describeTo(Description description) {
description.appendText("HttpGet with url ")
.appendDescriptionOf(urlMatcher);
}
};
}
31. Usage of the HttpGet matcher
when(handler.execute(argThat(
is(HttpGet(startsWith(“http://www.a.com”))))))
.thenReturn(response);
handler.handle(“http://www.a.com/some/path”);
verify(client).execute(argThat(is(HttpGet(
is(“http://www.example.com/some/path”)))));
32. The plot thickens
Moments after triumphantly running the test I
realized that in addition to verifying that the
request went to the appropriate URL, I had to
verify that some – but not all – HTTP headers
were copied to the proxy request and some new
ones were added to it.
33. Ad-hoc matchers to the rescue
1) Add the following parameter to the HttpGet
method:
final Matcher<Header[]> headersMatcher
2) Change the matchesSafetly() method:
public boolean matchesSafely(HttpGet httpGet) {
return urlMatcher.matches(httpGet.getURI().toString())
&& headersMatcher.matches(httpGet.getAllHeaders());
}
34. Ad-hoc matchers to the rescue
3) Write a matcher for the Header class:
Matcher<Header> Header(
final Matcher<String> name, final Matcher<String> value) {
return new TypeSafeMatcher<Header>() {
public boolean matchesSafely(Header header) {
return name.matches(header.getName())
&& value.matches(header.getValue());
}
}
}
35. Putting it all together
verify(client).execute(argThat(is(HttpGet( that the X-Wix-Base-Uri header
Asserts
contains the expected value (using the
is({URL matcher omitted for readability}),
WixUrl matchers we’ve seen before).
allOf(
hasItemInArray(
Header(
is("X-Wix-Base-Uri"),
Asserts that there’s no header by
isUrlThat( the name of X-Seen-By, no matter
what value it has
hasHost(“www.wix.com”), hasPath(myPath)))),
not(hasItemInArray(
Header(is("X-Seen-By"), any(String.class))))
)))));
This is a simplified version of the actual matcher from Hamcrest Core
For those of you who’re not familiar with Mockito, here’s how you use it
This has the disadvantage of being type-unsafe, but we’ll get back to this point later on.
Like the previous example, this is type-unsafe because we’re not sure that the Cat class even has a field named “kittens”, let alone its type
Matcher is the common ancestor for all Hamcrest matchers. Note that I removed a warning urging you not to implement Matcher<T>, extending BaseMatcher<T> instead.In most cases, you’ll want to extend TypeSafeMatcher<T>
This matcher works on the WixUrl class, which is a type-safe URL builder class from the Wix infrastructure.It’s a good example for the simple, yet somewhat confusing, structure of a matcher. Note that this matcher has one member, which is another string matcher for specifying the expected value. We could’ve used a string here, but using a Matcher<String> allows us to be more flexible when using this matcher.This pattern of replaying a matcher against the actual value is a core principle of Matcher programming.Note that our matcher extends TypeSafeMatcher, which implements the Matcher.matches() method and delegates to the matchesSafely() method after performing a type assertion followed by a cast.
Why do we need a Url matcher? Sometimes we don’t care about the query string, the host, the port, the protocol, etc. We could’ve used a string matcher such as contains() or endsWith() but this is more type safe, readable and illustrates the tested behavior more clearly.Note how the assertion error is much more readable than the one produced by assertEquals()
This one takes two matchers, one for the parameter name and one for the parameter value.Note another principle introduced here, that of creating a new matcher wrapping our matchers and replaying it against the actual value. Thus, we abstract away from the test the fact the WixUrl.params is a map. In fact, we lately changed it from a Map<String, String> to a Multimap<String, String> without breaking any test – I just changed the field type and the appropriate matcher class.
Note the use of the allOf() and anyOf() aggregate matchers that represent boolean AND and OR operations, respectively.
Based on a true storyThis class accepts an instance of HttpClient (Apache HttpComponents 4.0). I wanted to give it a mock of HttpClient, then stub and verify it.
I needed to be able to write matchers for the HttpGet class, for two reasons:1) It was much more readable than constructing an instance of it2) HttpGet takes on parameter, URI, and contains logic that deals with the HTTP protocol itself – not something that’s relevant for the test
Note, again, how we replay the expected value matcher against the actual value. This prevents the need to construct our own instance on HttpGet and populate it with the expected value. Also note that this is a factory method, creating an anonymous class. The method starts with a capital letter and is named according to the name of the class we’re matching against. This is a convention we developed here at Wix, but we find it useful and clear.
The use case here is that the proxy should send all traffic from www.wix.com/ to theproxied server, appending any nested path.Note that response can be either a real object constructed beforehand or a mock, but the mock must also be constructed before calling the when() method because of some Mockito limitation.Also note the reuse of our matcher both for stubbing the mock and verifying the desired behavior.
The matcher is for a Header array because HttpGet.getAllHeaders() returns an array
Note that without using Hamcrest, there’s no straightforward way to test for the inexistence of a value