Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit: How to mock today's date without passing it as an argument?

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?

like image 994
Andrew Avatar asked Aug 26 '11 21:08

Andrew


People also ask

Which method is used to create a mock with PHPUnit?

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.

What is assertion in PHPUnit?

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.

How do I run a single PHPUnit test?

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.


1 Answers

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?

like image 50
Jon Skeet Avatar answered Oct 22 '22 13:10

Jon Skeet