Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking The Time used by all instances of DateTime for testing purposes

Tags:

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:

  1. 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.

  2. Dynamically generate a dataset each time the test / suite is run.

So the question is: Is it possible to override DateTimes behaviour to always supply a specific time when requested?

like image 860
Ben Waine Avatar asked Oct 31 '11 10:10

Ben Waine


People also ask

Can you mock DateTime now?

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.

How do you mock a timestamp in Java?

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.

Why do we need mocking in unit testing?

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.


1 Answers

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

  • Stubbing Hard-Coded Dependencies by Sebastian Bergmann

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

like image 144
Gordon Avatar answered Sep 22 '22 12:09

Gordon