I'd like to be able to set the time for every instance of DateTime
instantiated for the duration of a PHPUnit or Behat Test.
I'm testing business logic relating to time. For example that a method in a class only returns events in the past or future.
Thing's I don't want to do if possible:
Write a wrapper around DateTime
and use this instead of DateTime
throughout my code. This would involve a bit of a re-write of my current code base.
Dynamically generate a dataset each time the test / suite is run.
So the question is: Is it possible to override DateTime
s behaviour to always supply a specific time when requested?
The wrapper implementation will access DateTime and in the tests you'll be able to mock the wrapper class. Use Typemock Isolator, it can fake DateTime. Now and won't require you to change the code under test. Use Moles, it can also fake DateTime.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf. setTimeZone(TimeZone. getTimeZone("PST")); Date NOW = sdf. parse("2019-02-11 00:00:00"); Timestamp time=new Timestamp(NOW.
Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.
You should stub the DateTime
methods you need in your tests to return expected values.
$stub = $this->getMock('DateTime'); $stub->expects($this->any()) ->method('theMethodYouNeedToReturnACertainValue') ->will($this->returnValue('your certain value'));
See https://phpunit.de/manual/current/en/test-doubles.html
If you cannot stub the methods because they are hardcoded into your code, have a look at
which explains how to invoke a callback whenever new
is invoked. You could then replace the DateTime class with a custom DateTime class that has a fixed time. Another option would be to use http://antecedent.github.io/patchwork
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