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
- Lesson 111: Mockito – Introduction and Integration
- Lesson 113: Writing Your First Unit Test with Mockito
- Lesson 118: Mockito – Writing Testable Code
- Lesson 120: Mockito – What Makes a Good Unit Test
- Lesson 129: Mockito – Test Doubles
- Lesson 130: Mockito – Configuring Stubs
- Lesson 133: Mockito – Stubs and their Default Return Values
- Lesson 140: Mockito String Matchers – anyString()
- Lesson 146 – Mockito: Stubs – Matching on any parameters of a given type