Skip to content

Supports mock time in the tests #508

@yankewei

Description

@yankewei

Currently, the project relies on native PHP time functions for time comparisons. However, this makes writing and running tests quite inconvenient in certain scenarios.

For example, in my project, I receive an access_token and an expires_in value from a third-party service. I wrote a test to assert that the token expires correctly (i.e., current time + expires_in). But since the current time is always changing, the expected expiration time differs on every test run, making the test unreliable.

Additionally, the code checks whether the token has expired based on real time. If I want to simulate a future or expired time in a test, I have to manually construct a specific time, which is tedious and error-prone.

To improve this, I’d like to propose a feature that allows us to “freeze” time during tests. This would enable more accurate and consistent time-related assertions. There are two potential approaches:
1. Use a date/time abstraction library, such as Carbon, which provides methods like Carbon::setTestNow() to freeze time. We could then use Carbon::now() throughout the codebase instead of native PHP time functions.
2. Introduce a simple time helper class, which provides a method to get the current time. In tests, we can override this method to return a fixed timestamp. There is already a PR available that demonstrates this approach.

Would the maintainers be open to adding support for one of these methods? I’m happy to help with implementation if needed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions