A Lesson by Craig Russell
This lesson describes how you can configure stubs to match on user-defined objects, as opposed to those classes built into Java.
Mockito has built-in matchers for the likes of anyString(), anyInt(), anyBoolean() and so on, but what happens when you need to match on a class you wrote yourself?
We describe the use of the any() matcher which matches on any types and any values, including nulls. Additionally, we describe the use of the overloaded any(Foo.class) matcher, which requires an instance of the user-defined class Foo to match; this will not match on nulls.
In this lesson you will learn:
- How to let a stub respond when you pass null as a parameter
- Configuring a stub to match on anything (any type and any value) passed as a parameter, which includes nulls
- Configuring a stub to match on only instances of a specific class, which excludes nulls
- The differences in syntax required when using Java 7 vs Java 8
Code for the Lesson
Pro members: Log in to view the code for this lesson!
Lessons in this course
- Mockito – Introduction and Integration
- Writing Your First Unit Test with Mockito
- Mockito – Writing Testable Code
- Mockito – What Makes a Good Unit Test
- Mockito – Test Doubles
- Mockito – Configuring Stubs
- Mockito – Stubs and their Default Return Values
- Mockito String Matchers – anyString()
- Mockito: Stubs – Matching on any parameters of a given type
- Mockito – Introduction to Mocks
- Mockito – Verifying a Method Was Never Called
- Mockito – Verifying a Method Was Called An Exact Number of Times
- Mockito – Verifying That a Method was Called a Minimum or Maximum Number of Times