PHPUnit Stub,我想替换测试中的函数

发布于 2024-12-14 11:05:29 字数 690 浏览 1 评论 0原文

所以我有一个运行 buildClass 方法的构建器,该方法应该是公共的,并且它需要几个参数。

在我的测试中,我想完全删除这些参数,并使用 PHPUnit 中的 Mock 添加完全不同的东西。

所以:来自:

class ClassBuilder{
  public function buildClass($id, $some, $vars){
    $class = new Class($id, $some, $vars);
    return self::getClass(db_Class, $class);
  }
}

所以你可能会在这里明白我的想法,我想做一个模拟,所以它在那里执行返回函数。

$myClassStub->getMock("ClassBuilder");
$myClassStub->->expects($this->any())
    ->method("buildClass")
    ->with($this->anything(), $this->anything())
    ->will($this->returnCallback("getClass"));

但我不知道它是如何运作的。我就是这么想的,但我根本不知道该把论点放在哪里。请在这里帮助我,非常感谢。

/马库斯

So I have this builder that runs a buildClass method which should be public, and it takes a couple of arguments.

In my test I want to remove those arguments completely and add something completely different using the Mock in PHPUnit.

So: from:

class ClassBuilder{
  public function buildClass($id, $some, $vars){
    $class = new Class($id, $some, $vars);
    return self::getClass(db_Class, $class);
  }
}

So you might get my idea here, I want to make a mock so it does the return function there.

$myClassStub->getMock("ClassBuilder");
$myClassStub->->expects($this->any())
    ->method("buildClass")
    ->with($this->anything(), $this->anything())
    ->will($this->returnCallback("getClass"));

But I have no idea how it works. This is how I thought it would be, but I have no clue where to put the arguments at all. Please help me out here, much appriciated.

/Marcus

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白云悠悠 2024-12-21 11:05:29

您可以省略 ->with($this->anything(), $this->anything()) ,除非它存在以确保您通过至少 2该函数的参数。

除了你之外,我所了解的是你想返回一个不同的班级。在这种情况下,我建议这样做:

$yourClassToReturn = "..."; // create the class here

$myClassStub->getMock("ClassBuilder");
$myClassStub->expects($this->any())
    ->method("buildClass")
    ->with($this->anything(), $this->anything())
    ->will($this->returnValue($yourClassToReturn));

You can just leave out the ->with($this->anything(), $this->anything()) exepct if it is there to make sure that you pass at least 2 arguments into that function.

Apart from you that I've understood is that you want to return a different class. In that case I'd suggest doing:

$yourClassToReturn = "..."; // create the class here

$myClassStub->getMock("ClassBuilder");
$myClassStub->expects($this->any())
    ->method("buildClass")
    ->with($this->anything(), $this->anything())
    ->will($this->returnValue($yourClassToReturn));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文