I am testing a method on my class that does some date checking. The problem is that the method depends on today's date (which changes every day), which makes this difficult to test. How can I mock today's date so that my tests will still pass tomorrow?
PHPUnit provides methods that are used to automatically create objects that will replace the original object in our test. createMock($type) and getMockBuilder($type) methods are used to create mock object. The createMock method immediately returns a mock object of the specified type.
PHPUnit assertTrue() Function The assertTrue() function is a builtin function in PHPUnit and is used to assert whether the assert value is true or not. This assertion will return true in the case if the assert value is true else returns false.
You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder. You can also run a single test by providing the path to the test file. You use the --verbose flag to get more information on the test status. The output shows that we ran 1 test, and made 3 assertions in it.
I know nothing about PHP, but in both Java and C# I would pass in a "clock" of some description - not today's date itself, but an object which you can ask for the current date/time. Then in unit tests you can pass in an object which can give any date you want - including one that's hard-coded into the tests.
Does that work in PHP too?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With