Skip to content

Comments

Add withTestNow() for scoped time mocking#498

Merged
markstory merged 1 commit into3.nextfrom
add-with-test-now
Feb 24, 2026
Merged

Add withTestNow() for scoped time mocking#498
markstory merged 1 commit into3.nextfrom
add-with-test-now

Conversation

@dereuromark
Copy link
Member

Summary

  • Adds a new static method withTestNow() that temporarily sets the test time, executes a callback, and then restores the previous test time state
  • Uses try/finally to ensure state restoration even when callback throws exceptions
  • Includes comprehensive tests for basic usage, nested calls, and exception handling

Use Cases

This is useful for:

  • Nested time mocking scenarios
  • Tests that need to temporarily override a global mock time set in setUp()
  • Clean time mocking that automatically restores state

Example

// Basic usage
$result = Chronos::withTestNow('2023-06-15 12:00:00', function () {
    return Chronos::now()->format('Y-m-d');
});
// $result === '2023-06-15'

// Nested calls work correctly
Chronos::setTestNow('2020-01-01');
Chronos::withTestNow('2023-06-15', function () {
    // Here now is 2023-06-15
    Chronos::withTestNow('2024-12-25', function () {
        // Here now is 2024-12-25
    });
    // Back to 2023-06-15
});
// Back to 2020-01-01

Related

Inspired by Carbon's withTestNow() implementation and the fix in briannesbitt/Carbon#3283 which ensures the previous test time is restored (not unconditionally reset to null).

Adds a new static method `withTestNow()` that temporarily sets the test
time, executes a callback, and then restores the previous test time state.

This is useful for:
- Nested time mocking scenarios
- Tests that need to temporarily override a global mock time set in setUp()
- Clean time mocking that automatically restores state

The method correctly restores the previous state even when the callback
throws an exception, using a try/finally block.

Inspired by Carbon's withTestNow() implementation and the fix in
briannesbitt/Carbon#3283.
@markstory markstory merged commit 4a83d99 into 3.next Feb 24, 2026
8 checks passed
@markstory markstory deleted the add-with-test-now branch February 24, 2026 05:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants