Can I “Mock” time in PHPUnit?

后端 未结 11 494
梦谈多话
梦谈多话 2020-11-29 01:53

... not knowing if \'mock\' is the right word.

Anyway, I have an inherited code-base that I\'m trying to write some tests for that are time-based. Trying not to be <

11条回答
  •  北海茫月
    2020-11-29 02:29

    Here's an addition to fab's post. I did the namespace based override using an eval. This way, I can just run it for tests and not the rest of my code. I run a function similar to:

    function timeOverrides($namespaces = array()) {
      $returnTime = time();
      foreach ($namespaces as $namespace) {
        eval("namespace $namespace; function time() { return $returnTime; }");
      }
    }
    

    then pass in timeOverrides(array(...)) in the test setup so that my tests only have to keep track of what namespaces time() is called in.

提交回复
热议问题