---
title: "Faking Time"
url: "https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/faking-time.md"
canonical: "https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/faking-time/"
tags: []
author: "Roy Osherove"
description: "Lesson 15 of 21 in The Art of Unit Testing and TDD in Java (Day 3), 5:46. 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/"
---

# Faking Time

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 3

Lesson 15 of 21

Duration: 5:46 [Watch on YouTube](https://www.youtube.com/watch?v=jpvaPGdV8ts)

Learn a simple technique to [handle time in your tests](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-7#ch07lev1sec5 "Cross-cutting concerns injection (The Art of Unit Testing, 2nd ed., ch. 7)"), and in your production code.

## In this lesson

Roy Osherove explains why tests should not depend on the [current date and time](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_64 "Stubbing out time with parameter injection (The Art of Unit Testing, 3rd ed., ch. 3)"), and why [extract and override](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-3#ch03lev1sec5 "Variations on refactoring techniques (The Art of Unit Testing, 2nd ed., ch. 3)") or a [time provider 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)") in every constructor does not suit a [cross-cutting concern](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-7#ch07lev1sec5 "Cross-cutting concerns injection (The Art of Unit Testing, 2nd ed., ch. 7)") like time. Instead he uses a static time provider class in the production code that tests can force to a given time and reset afterwards, for example in an after method. For the machine name in the next exercise he suggests extract and override.

## Transcript

1,006 words

[\[00:02\]](https://www.youtube.com/watch?v=jpvaPGdV8ts&t=2s) Okay, let's talk about [controlling time](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-7#ch07lev1sec5 "Cross-cutting concerns injection (The Art of Unit Testing, 2nd ed., ch. 7)") and space. One of the requirements in the document that we have is that we want to manipulate the current time. We want to format a string with a date. Now, the problem with dates are that they keep changing. So if we actually use the current date and time in our tests, what's going to happen is that every time we run the test, it's actually going to be a different test. We want our test to be repeatable always so that we can have the [safe green zone](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-7#ch07lev1sec2 "Mapping out tests based on speed and type (The Art of Unit Testing, 2nd ed., ch. 7)").

[\[00:36\]](https://www.youtube.com/watch?v=jpvaPGdV8ts&t=36s) If you remember, a safe green zone is when you right click and run and all the tests should be green no matter what, as long as the production code is okay. We only want them to fail when the production code is okay, not when the time changes. So instead what we want to do if we want to implement something like this but we want to test it there are several ways to get around this. For example we can create a virtual method that gets the current time.

[\[01:07\]](https://www.youtube.com/watch?v=jpvaPGdV8ts&t=67s) So we can say extract method oops selected block. Oh yeah, of course. Extract method get time. And then we can make this virtual protected sorry. And then we can override it and return whatever time we want in our tests. That looks kind of easy.

[\[01:38\]](https://www.youtube.com/watch?v=jpvaPGdV8ts&t=98s) However, that could be a bigger problem than you think. And the reason is because time is usually crosscutting. Everyone uses it. And so what that will require of you is that every class that uses time, you're going to have to [extract and override](https://osherove.com/blog/2005/6/16/mock-objects-vs-quotinherit-amp-overridequot.html "Mock Objects vs. \"Inherit & Override\" (osherove.com)") over that class. And that's going to be a big problem. So that might not be a good idea in this case. What about extracting interface? What if each class had a [time provider 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)") that it gets in the constructor? Well, you have the same problem because time is usually used in so many places.

[\[02:10\]](https://www.youtube.com/watch?v=jpvaPGdV8ts&t=130s) You're going to have to inject time into so many classes, it becomes very very hard to read and maintain. Although those approaches would work, I don't think they're the best approaches in this case when we have a cross cutting concern like time. So in that kind of case, what I would do is I would actually create a time provider class, an abstraction over the current time. This is an example of what it might look like. and it can give me the current date. So I would have the current date and time.

[\[02:43\]](https://www.youtube.com/watch?v=jpvaPGdV8ts&t=163s) So everyone in the production code would have to use this class. So that means that I'm changing the way people work with time and I do [code reviews](https://osherove.com/blog/2007/3/13/test-reviews-vs-code-reviews-some-helpful-tips.html "Test Reviews Vs. Code Reviews - Some Helpful Tips (osherove.com)") to make sure that nobody uses date directly. But instead I want them to always use time provider which is part of the production code. But the nice thing about time provider is that I can have methods that say I want you to force the current the current time and then at the end of my test I can reset so that it sets the date to null and then it will use the current date

[\[03:14\]](https://www.youtube.com/watch?v=jpvaPGdV8ts&t=194s) When someone uses it. So this is like almost like a very way a simple singleton approach to to to having time. But this abstraction actually makes our test very readable. At the beginning of our test we force the time to be something. At the end of our test we reset the time. We can even have an after method like a [tear down](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-9#sigil_toc_id_171 "Setting up and tearing down (The Art of Unit Testing, 3rd ed., ch. 9)") method in [JUnit](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-2#sigil_toc_id_39 "The xUnit frameworks (The Art of Unit Testing, 3rd ed., ch. 2)") that will reset the time automatically for all the tests. So we don't have to worry about it. And this is the case where I said that sometimes before and after methods make sense when you want to reset static stuff.

[\[03:47\]](https://www.youtube.com/watch?v=jpvaPGdV8ts&t=227s) So this is an example of something that is static because we don't want to inject the time into all the instances of our of our objects. >> Yeah. So this is a good way to simulate dates. For example, you can say I want this component to to give a notification after 14 days. Then you can basically get the time provider to change the current date. Now another thing that we can do is if we if we have things that keep for example timers or time based things that change every second.

[\[04:20\]](https://www.youtube.com/watch?v=jpvaPGdV8ts&t=260s) One of the ways that that we can do it is we can we can make this a bit more interesting by saying that we can get events from the time provider for example on every second that's passing and then we can trigger those events and say I want you to trigger as if 10 seconds just passed etc. So if we have eventbased objects that are listening to the current time based on the thread or something, we can instead change it directly over here. So we don't have to wait all that time. Either way, the time provider is a good abstraction in terms of design because it really removes the time away from your application and it's also good for the tests.

[\[04:58\]](https://www.youtube.com/watch?v=jpvaPGdV8ts&t=298s) So what I want you to do is I want you to solve from the timebased problem onwards using a time provider. However, one of the things we'll have to do is to also get the machine name. The machine name, it could be crosscutting or it wouldn't. Usually machine name you don't get in all all in all the all the places. So machine name would be a good candidate for extract and override. So in the next scenario, you will need to [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)") both the machine name and the time.

[\[05:28\]](https://www.youtube.com/watch?v=jpvaPGdV8ts&t=328s) So you would have a combination of time provider and extract and override. they want you to to use both of them together. Okay. And after that, you can continue to future instances and you'll see that extract and override works very well for future instances as well.

## Related

- [Cross-cutting concerns injection](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-7#ch07lev1sec5) · The Art of Unit Testing, 2nd ed., ch. 7

    The 2nd edition's section on cross-cutting concerns injection, the static time provider approach used for time here.

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

    The 3rd edition's section on stubbing out time with parameter injection, an alternative way to control the clock.

### Also linked in this lesson

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

- [Extracting a common interface](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-3#sigil_toc_id_74), ch. 3
- [Setting up and tearing down](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-9#sigil_toc_id_171), ch. 9
- [The xUnit frameworks](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-2#sigil_toc_id_39), ch. 2

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

- [Variations on refactoring techniques](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-3#ch03lev1sec5), ch. 3
- [Mapping out tests based on speed and type](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-7#ch07lev1sec2), ch. 7
- [The difference between mocks and stubs](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4#ch04lev1sec2), ch. 4

#### osherove.com

- [Mock Objects vs. "Inherit & Override"](https://osherove.com/blog/2005/6/16/mock-objects-vs-quotinherit-amp-overridequot.html)
- [Test Reviews Vs. Code Reviews - Some Helpful Tips](https://osherove.com/blog/2007/3/13/test-reviews-vs-code-reviews-some-helpful-tips.html)

[Previous lesson Extract And Override Refactoring](https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/extract-and-override-refactoring/) [Next lesson Faking Futures](https://courses.osherove.com/courses/the-art-of-unit-testing-and-tdd-in-java/faking-futures/)


---

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