---
title: "Introduction to Mocks and Stubs"
url: "https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/introduction-to-mocks-and-stubs.md"
canonical: "https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/introduction-to-mocks-and-stubs/"
tags: []
author: "Roy Osherove"
description: "Lesson 8 of 21 in The Art of Unit Testing and TDD in Java (Day 2), 10:30. Free video by Roy Osherove."
usage: "Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page)."
license: "https://creativecommons.org/licenses/by/4.0/"
---

# Introduction to Mocks and Stubs

1. [Courses](https://courses.osherove.com/#courses)
2. [The Art of Unit Testing and TDD in Java](https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/)
3. Day 2

Lesson 8 of 21

Duration: 10:30 [Watch on YouTube](https://www.youtube.com/watch?v=4fdkCJuxAfo)

In this talk we learn about [mocks and stubs](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-4#sigil_toc_id_79 "The importance of differentiating between mocks and stubs (The Art of Unit Testing, 3rd ed., ch. 4)") using a simple problem of notifying a logger of something that happened.

## In this lesson

Roy Osherove explains how to test a [call to a third party](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_19 "Exit point types (The Art of Unit Testing, 3rd ed., ch. 1)") with a [string calculator](https://osherove.com/tdd-kata-1 "TDD Kata 1 - String Calculator (osherove.com)") that must send each sum to a slow logger, by adding [a logger interface](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_74 "Extracting a common interface (The Art of Unit Testing, 3rd ed., ch. 3)") and a [handwritten fake](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4#ch04lev1sec3 "A simple handwritten mock example (The Art of Unit Testing, 2nd ed., ch. 4)") logger class. He defines a [fake](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4#ch04lev1sec2 "The difference between mocks and stubs (The Art of Unit Testing, 2nd ed., ch. 4)") as something that looks like something else, a [mock](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-4#sigil_toc_id_76 "Interaction testing, mocks, and stubs (The Art of Unit Testing, 3rd ed., ch. 4)") as a fake you assert against and a [stub](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_62 "Reasons to use stubs (The Art of Unit Testing, 3rd ed., ch. 3)") as any other fake, and allows [at most one mock per test](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4#ch04lev1sec5 "One mock per test (The Art of Unit Testing, 2nd ed., ch. 4)"). The fake is passed in through [constructor injection](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_72 "Constructor injection (The Art of Unit Testing, 3rd ed., ch. 3)"), and a [test name](https://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html "Naming standards for unit tests (osherove.com)") such as add always calls logger shows that a mock object is involved.

## Transcript

1,701 words

[\[00:04\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=4s) Okay, so yesterday was maybe a very simplistic view of the world. Obviously, we were always able to get a return value from our methods. But today we're going to look at a very different very different scenarios. Today we're going to look at the the case of the calling a third party. We actually yesterday we did do the first the first scenario which is returning a value.

[\[00:35\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=35s) We didn't actually have any tests for state-based tests yet. But we'll al hopefully have some today as well. But today we're going to focus on what happens when you call a third party. So just as a reminder, we have a [unit of work](https://osherove.com/blog/2020/3/12/unit-testing-entry-points-and-exit-points "Unit Testing Entry and Exit Points (osherove.com)") that starts with a public API and now the requirement will be that there is a [call to a third party](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_19 "Exit point types (The Art of Unit Testing, 3rd ed., ch. 1)"), maybe a logger or something like that. And the way that we're going to to test that is

[\[01:06\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=66s) We're going to have to get around the fact that we don't have control of the third party. For example, if it's a logger that's written by a different team, if it's a logger that's written by a different team, then maybe their code doesn't work yet. Maybe it has a bug. So our test will fail if we actually use their code. Maybe it works very slowly. So our test will be very slow. So we want to get get control over the third party. One way we can do it is to abstract it away and create a [mock object](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4 "Interaction testing using mock objects (The Art of Unit Testing, 2nd ed., ch. 4)") something that looks exactly like the third party.

[\[01:40\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=100s) But we do have control over it. And then the next leap of faith is is that we assume that if our mock object got called then the third party got called. Now it is a leap of faith because we are essentially decoupling our system from another system and we cannot really prove that the other system gets called without an [integration test](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_25 "Integration tests (The Art of Unit Testing, 3rd ed., ch. 1)"). So this is the next best step which is to assume that if the mock object got called a third party system got called.

[\[02:13\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=133s) And this is especially true when what we're going to do is to abstract away things either with adapters abstra interfaces and things like that. We have to assume that the system will eventually work. One way to make sure that actually happens is to have both [unit tests](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_17 "Defining unit testing, step by step (The Art of Unit Testing, 3rd ed., ch. 1)") and integration tests at the same time. That means that unit tests are definitely not enough for you to know that your system is working. Unit tests are just a way for you to develop the system.

[\[02:44\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=164s) They're not a way for you to make sure the system works. To make sure the system works, you have to have integration and acceptance tests. >> There is no other way because at some point things are going to try to talk to each other and that's the integration points. So here's a very simplistic scenario. If we take the [string calculator](https://osherove.com/tdd-kata-1 "TDD Kata 1 - String Calculator (osherove.com)") that we've all just written and now we'll have a requirement that let's assume there's a class called slow logger.

[\[03:15\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=195s) Now I'm calling it slow logger so that you remember not to use it in your own tests. But the requirement is that whenever you call add and you give it some numbers the sum that's returned is also sent to the logger. So we have some kind of auditing on the system. So again the requirement is that there is an arrow between string calculator and slow logger and every time you call add slow logger gets called. Now again slow logger here is a third party system.

[\[03:46\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=226s) We don't have control over it. If we could make it run in memory and make it run fast, maybe we do have control over it. But the fact is this is a slow logger because it uses threads and five different web services inside. Takes 5 seconds to run. We can't use it in our actual unit test. So the be next best thing is to try to create something that looks like the slow logger. And in Java, one of the best ways to make something look like another thing is to create an interface.

[\[04:18\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=258s) Makes them look the same. So we create we in we introduce a new interface into the system. We'll call it logger. And then we make slow logger implement that interface. But we need one more step. We need something that we can control. So we create a new class. I'm not using any kind of [isolation frameworks](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-5#sigil_toc_id_99 "Defining isolation frameworks (The Art of Unit Testing, 3rd ed., ch. 5)") just yet. What I'm going to do is I'm going to create this handwritten. And this is an important skill that you need to know not to use an isolation or a mocking framework, but to do things without them.

[\[04:51\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=291s) Once you do, you can understand how these other frameworks actually work. You can choose to use them or not. So, we're going to create a new class called [fake](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-5#ch05lev1sec2 "Dynamically creating a fake object (The Art of Unit Testing, 2nd ed., ch. 5)") logger in our test project. And fake logger is going to implement the [logger interface](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_74 "Extracting a common interface (The Art of Unit Testing, 3rd ed., ch. 3)") just like slow logger. But the difference is that fake logger is our class. So we can make it do whatever we want. For example, we can add a public field to it. We can we can we can override the write method and of course not do anything so that it will run fast.

[\[05:27\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=327s) So it looks like this. In my tests, the quickest way is to actually create my own little class called fake logger. Now, why am I not calling it mock logger? Any ideas? Because it might not be a mock object. So, let's talk about the the naming for a second. I call it fake logger because it looks like something else,

[\[05:58\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=358s) But it might not always be a mock object. What's the difference between a fake and a mock? A fake is something that looks like something else. A mock is a fake that I assert against. Okay? So if I assert against it, it's a mock object. Okay? Otherwise, it's a [stub](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-3#ch03lev1sec1 "Introducing stubs (The Art of Unit Testing, 2nd ed., ch. 3)"). But either way, they're both fakes. Okay? So a fake can either be a mock or a stub based on how you use it.

[\[06:31\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=391s) Now, why is it important to actually distin distinct to have a distinction between them? because you should only have a single mock per test at the worst case because you only want to check one thing per test. You can have multiple stubs but only a single mock object because a mock object is an [end result](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_18 "Entry points and exit points (The Art of Unit Testing, 3rd ed., ch. 1)") of the unit of work. We want to check one end result per test. If we check multiple end results and one of them fails, the others will never execute. So we won't know what's going on. So a mock object is really an assert, a hidden assert against a single end result.

[\[07:08\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=428s) Anyway, I take my fake logger and I override the write method and I implement logger. And notice that I just create a public field and I set it from the variable. I make it the [simplest code](https://osherove.com/blog/2010/1/6/tdd-4-questions-that-will-help-you-create-the-simplest-thing.html "TDD: 4 questions that will help you create the simplest thing that could possibly work (osherove.com)") that I could possibly write because this doesn't exist anywhere but in the context of my unit tests. And then I'm going to write a new test right here. This is how my test would look. Notice first of all the naming add that's the entry point of the unit of work when called because I don't have a specific scenario it or I can say either always or when called.

[\[07:48\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=468s) So add always calls logger or add when called calls logger. And the word calls logger the word calls is important because I'm not actually doing logging. I'm calling a third party. So the naming is important and by looking at the name I can tell that there's probably a mock object in there. The second thing that I do that I create an instance of the fake logger in my unit test and then I send that fake logger somehow into the string calculator.

[\[08:21\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=501s) Now the string calculator has to have an a reference to the to the logger and one of the best ways to do it is by doing [constructor injection](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_72 "Constructor injection (The Art of Unit Testing, 3rd ed., ch. 3)") by by adding an argument to the constructor of string calculator. Now this also makes sure that this is nonoptional. So whoever is using string calculator has to send in a logger. If I wanted to make it optional I could make it a setter public setter or something. But I like to make things explicit so that I know exactly what my dependencies are.

[\[08:54\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=534s) And this also helps later if I'm going to use things like Spring to to create to do [dependency injection](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_65 "Dependencies, injections, and control (The Art of Unit Testing, 3rd ed., ch. 3)") and inversion of control. Either way, I just added an argument to the string calculator and I'm going to send in the mock logger. And notice that I used a fake but I named the variable mock because in this unit test the fake logger is being used as a mock object.

[\[09:25\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=565s) And then I call add and I assert against the mock object. And this is important. I can look at the I can when I review this test I can say okay so you're asserting on a mock object. If I happen to call it mock stub or sorry lo log stub or stub log, it wouldn't make sense to say assert on a stub because a stub is something that just makes happy noises when you so that you can test something else. I only want to assert against mock objects.

[\[09:56\]](https://www.youtube.com/watch?v=4fdkCJuxAfo&t=596s) So I just save things into the string of mock logger here. I save things into written and then I assert that written actually has something. And this is what the string calculator looks like. That's the only difference that I've made. And notice that the difference is that it takes a logger. The logger is actually part of production code. The fake logger is part of test code. So the logger interface now abstracts away the knowledge from string calculator. So string calculator doesn't need to know what is the type of logger that it

## Related

- [Depending on a logger](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-4#sigil_toc_id_77) · The Art of Unit Testing, 3rd ed., ch. 4

    The 3rd edition's section on depending on a logger, the same third-party logger problem used in this lesson.

- [Interaction testing, mocks, and stubs](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-4#sigil_toc_id_76) · The Art of Unit Testing, 3rd ed., ch. 4

    Section introducing interaction testing, mocks and stubs, the definitions this lesson gives for fakes.

- [One mock per test](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4#ch04lev1sec5) · The Art of Unit Testing, 2nd ed., ch. 4

    The 2nd edition's section on one mock per test, the rule stated in this lesson.

- [TDD Kata 2 - Interactions](https://osherove.com/tdd-kata-2) · osherove.com

    The Interactions kata extending String Calculator with a logger, forcing the mocks and stubs shown here.

### Also linked in this lesson

#### The Art of Unit Testing, 3rd ed.

- [Exit point types](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_19), ch. 1
- [Extracting a common interface](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_74), ch. 3
- [Reasons to use stubs](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_62), ch. 3
- [Constructor injection](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_72), ch. 3
- [The importance of differentiating between mocks and stubs](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-4#sigil_toc_id_79), ch. 4
- [Integration tests](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_25), ch. 1
- [Defining unit testing, step by step](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_17), ch. 1
- [Defining isolation frameworks](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-5#sigil_toc_id_99), ch. 5
- [Entry points and exit points](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_18), ch. 1
- [Dependencies, injections, and control](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_65), ch. 3

#### The Art of Unit Testing, 2nd ed.

- [A simple handwritten mock example](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4#ch04lev1sec3), ch. 4
- [The difference between mocks and stubs](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4#ch04lev1sec2), ch. 4
- [Interaction testing using mock objects](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4), ch. 4
- [Dynamically creating a fake object](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-5#ch05lev1sec2), ch. 5
- [Introducing stubs](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-3#ch03lev1sec1), ch. 3

#### osherove.com

- [TDD Kata 1 - String Calculator](https://osherove.com/tdd-kata-1)
- [Naming standards for unit tests](https://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html)
- [Unit Testing Entry and Exit Points](https://osherove.com/blog/2020/3/12/unit-testing-entry-points-and-exit-points)
- [TDD: 4 questions that will help you create the simplest thing that could possibly work](https://osherove.com/blog/2010/1/6/tdd-4-questions-that-will-help-you-create-the-simplest-thing.html)

[Previous lesson Some Numbers](https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/some-numbers/) [Next lesson Demo - Mock Objects](https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/demo-mock-objects/)


---

## About the author

**Roy Osherove**: Senior Solutions Architect at AWS working on AI for production and AI-driven development; author of The Art of Unit Testing and Elastic Leadership, with about 20 years of consulting and training on unit testing, TDD, team leadership and continuous delivery.

### Sites

- [RobotPaper](https://robotpaper.ai/): This blog: AI patterns and anti-patterns, AI and coding agents, and engineering leadership.
- [osherove.com](https://osherove.com): Roy's personal site. Author of The Art of Unit Testing and Elastic Leadership; consulting and training on unit testing, TDD, team leadership and continuous delivery, plus about 20 years of blog posts.
- [The Art of Unit Testing](https://www.artofunittesting.com): The Art of Unit Testing, 3rd Edition (Manning): readable, maintainable, trustworthy unit tests, plus TDD workshops in C#, JavaScript, Java and Kotlin.
- [5whys.com](https://www.5whys.com): Roy's writing on software team leadership: self-organizing teams, surviving chaos, learning mode and the Elastic Leadership model.
- [Pipeline Driven](https://pipelinedriven.org): Continuous delivery and DevOps practices: build patterns, pipeline-friendly testing, DevOps metrics and enterprise DevOps.
- [Elastic Leadership](https://www.elasticleadership.com): Elastic Leadership, Roy's framework for software team leaders (survival, learning and self-organizing modes).

### Social

- X: https://x.com/royosherove
- LinkedIn: https://www.linkedin.com/in/osherove/

### Contact

- Contact form: https://forms.gle/jQSx5KoXvrVA1JCK7

### License

Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page). License: https://creativecommons.org/licenses/by/4.0/
