---
title: "Demo - Mock Objects"
url: "https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/demo-mock-objects.md"
canonical: "https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/demo-mock-objects/"
tags: []
author: "Roy Osherove"
description: "Lesson 9 of 21 in The Art of Unit Testing and TDD in Java (Day 2), 9:17. 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/"
---

# Demo - Mock Objects

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 9 of 21

Duration: 9:17 [Watch on YouTube](https://www.youtube.com/watch?v=XKlVqR164WY)

A short demo showing how you can implement the [extract interface pattern](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)"), [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 hand written [mocks](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)") to solve our problem of controlling a 3rd party logger in a [unit test](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)").

## In this lesson

Roy Osherove writes the add always calls logger test first, as if everything already existed, with 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)") logger that saves the text in a public written field and is passed to the [string calculator](https://osherove.com/tdd-kata-1 "TDD Kata 1 - String Calculator (osherove.com)")'s constructor. Because the other tests create the calculator through the make calc helper, the new constructor argument changes one place, where a fake logger is passed in as 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)"). He sees only the new test fail, makes add call the logger, and has to add throws Throwable to the tests, which he dislikes.

## Transcript

1,231 words

[\[00:02\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=2s) So what I'm going to do is I'm going to create a new test. I'm going to start with scr from scratch. I'm going to write a test for [string calculator](https://osherove.com/tdd-kata-1 "TDD Kata 1 - String Calculator (osherove.com)") that adds this dependency. And because this is test driven, I'm going to write my test before I do anything else. So I'm going to say test public void. I need to give it a good name. The name would be well add is the [entry point](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)"). I might say always

[\[00:32\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=32s) Because it always does something. It's not only when a specific something behavior happens. I want add to always call a logger. Then I can say calls logger. Okay. So now what we're going to do is we're going to pretend that the world that I would like to have in my code already exists.

[\[01:07\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=67s) I'm going to write my test as if everything I need already exists. For example, I might say I would need a [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. I might say my fake logger. Now I I already wrote this for you guys in the demo. So you're going to see that this class is already written but I might say the fake logger just so that you don't see it in the IntelliSense fake logger [mock](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)") log equals new the fake logger.

[\[01:40\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=100s) What else? We want to send the fake logger into the string calculator. I want to say string calculator equals I'm not going to use make calc anymore for this because when I use mock objects I want to have an explicit dependency. I want to be able to control the things that I send into the constructor. So I a don't want to use the [helper method](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-7#ch07lev1sec6 "Building a test API for your application (The Art of Unit Testing, 2nd ed., ch. 7)") and b if I did choose to use the helper method it would become very very messy very fast. somehow it would have to save the mock object in a in a variable in the class and then I would have to figure out which it would become very unreadable.

[\[02:16\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=136s) So I'm just going to make it right now direct. So I'm going to say new string calculator and I'm going to send in mock log. Of course this won't compile yet. But remember the point is to finish the test and say I think this is good enough. I understand the problem. this is how I want to test it and then I make everything work according to that. I might say scadd well this is the simplest I can think of and assert equals0

[\[02:55\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=175s) Into the logger mock log dot written or written and if I'm happy with that I can go ahead and create a class right above here because no one else is currently using this. If I see that I have multiple tests in multiple classes using those fake objects, I can then refactor and move it into a separate file. But right now, I want everything as close as possible to the test so that the serial killer doesn't need to go to my house and ask me what the hell that is.

[\[03:29\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=209s) Class the fake logger implements logger. Now, logger doesn't exist yet, obviously, but I'm going to pretend it exists for a second. And here I'm just going to say public void write string text. I'm just going to say written is

[\[03:59\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=239s) Equal to whatever the text is. So, this should be enough. Now I've actually gone ahead and created the slow logger and I do have an interface for logger which I wrote before. So what I'm going to do is I'm just going to connect to that. I'm just going to say logger import the class.

[\[04:29\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=269s) But I do need a field here. Put it indirectly in this class and make it public. I don't need a getter and a setter because I want this code to be simple. There's no reason to hide and protect anything because this class is only for tests. Now I still have to go and add the parameter to the constructor. So I'm going to go ahead and say that the parameter type is logger.

[\[05:02\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=302s) I'm going to call it log because the production code doesn't need to know that there is such a thing as mock objects at all. So it has to be purely abstract So that's the difference. Now remember this is [TDD](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_27 "Test-driven development (The Art of Unit Testing, 3rd ed., ch. 1)"). So I want my test after it compiles. I want to see it fail. So I'm not adding the functionality of calling the logger just yet. If I run this test

[\[05:39\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=339s) I oh now there's a different compilation error and you're going to find this as well. And remember we talked about [maintainability](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-8 "Maintainability (The Art of Unit Testing, 3rd ed., ch. 8)") of the test. Now I have 10 tests for string calculator but now I've added a constructor argument. Now I would have to change all my tests if I if all of them did new string calculator. Luckily I do have the make calc method right here which is which means I only have to change one place. Now the question is what am I going to send as an argument? The answer is I'm just going to send in a fake logger.

[\[06:10\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=370s) But this time not no one is going to assert against it. Right? That means that for all the other tests they're just going to have 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)") logger. Just makes happy noises. doesn't do anything. So now very easily I can just say just send it a new the fake logger. That's it. If I run the test now they should all be passing except the one that I wrote. Where are you? Okay.

[\[06:45\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=405s) And I can see now expected got zero but actual was nothing. So only my test the last test is failing which is what I wanted. So it took me only a few seconds to make all the other tests pass by sending in a stub and only in a single test am I using a mock object. Okay. And this is where the maintainability aspect comes in. Otherwise this would be hell now to go and send a new one in each one in each other test. So now I can go in and say okay let's go to the string calculator

[\[07:22\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=442s) And when I call add I can say blah blah blah where is it well I just have to find somehow the default value right so I might say put it right there and say log write dot plus default value and of course this is bad because I'm repeating myself but I can refactor it later after the test passes

[\[08:03\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=483s) Value to string let's see oh I need to handle the exception Okay. And that means probably that now I have to go and handle the exceptions in all the other cases. Now I have to go here. And this is the part that I hate coming from many different languages. Adding that throwable stuff is just horrible to me. I just don't like it.

[\[08:34\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=514s) Now I have to go to all the tests and add the throw throws throwable whatever that means. Ah so you see you do it once and then you're done with it but it's still pretty horrible in terms of terms of usability and maintainability. Okay. And let's see if that would work. Start adding.

[\[09:14\]](https://www.youtube.com/watch?v=XKlVqR164WY&t=554s) Are we done yet? Are we there yet? Thank you.

## Related

- [A simple handwritten mock example](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4#ch04lev1sec3) · The Art of Unit Testing, 2nd ed., ch. 4

    The 2nd edition's simple handwritten mock example, like the fake logger with a written field built in the demo.

- [Constructor injection](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_72) · The Art of Unit Testing, 3rd ed., ch. 3

    The 3rd edition's section on constructor injection, how the demo passes the fake logger to the calculator.

- [Extracting a common interface](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_74) · The Art of Unit Testing, 3rd ed., ch. 3

    Section on extracting a common interface, the extract interface step behind the logger interface.

- [Changes in the production code’s API](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-8#sigil_toc_id_157) · The Art of Unit Testing, 3rd ed., ch. 8

    Section on production API changes breaking tests, why the make calc helper keeps the constructor change in one place.

### Also linked in this lesson

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

- [Reasons to use stubs](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_62), ch. 3
- [Interaction testing, mocks, and stubs](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-4#sigil_toc_id_76), ch. 4
- [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
- [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
- [Test-driven development](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_27), ch. 1
- [Maintainability](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-8), ch. 8

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

- [The difference between mocks and stubs](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4#ch04lev1sec2), ch. 4
- [Dynamically creating a fake object](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-5#ch05lev1sec2), ch. 5
- [Interaction testing using mock objects](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4), ch. 4
- [Building a test API for your application](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-7#ch07lev1sec6), ch. 7
- [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)

[Previous lesson Introduction to Mocks and Stubs](https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/introduction-to-mocks-and-stubs/) [Next lesson Terminology](https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/terminology/)


---

## 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/
