简体   繁体   English

如何模拟界面的一种方法?

[英]How do I mock one method of an interface?

I want to mock the validate method of an interface, and have all the other interface methods stubbed return null (I don't really care what happens to them), but there doesn't appear to be a way to do this easily. 我想模拟一个接口的validate方法,并让所有其他接口方法存根返回null(我真的不关心它们会发生什么),但似乎没有办法轻松地做到这一点。

Here's what I have: 这就是我所拥有的:

    $validator = $this
        ->getMockBuilder('Symfony\Component\Validator\Validator\ValidatorInterface')
        ->setMethods(array('validate'))
        ->getMock();

    $validator
        ->expects($this->once())
        ->method('validate')
        ->willReturn(array());

    $validator->validate();

Running this gives me a fatal error: 运行这个给我一个致命的错误:

Class Mock_ValidatorInterface_56c4c003 contains 6 abstract methods and must therefore be declared abstract or implement the remaining methods 类Mock_ValidatorInterface_56c4c003包含6个抽象方法,因此必须声明为abstract或实现其余方法

So - I need to somehow tell PHPUnit to stub the other methods that the interface requires. 所以 - 我需要以某种方式告诉PHPUnit存根接口所需的其他方法。 What's the right way to do this? 这样做的正确方法是什么?

Declare all the interface's methods in ->setMethods() . ->setMethods()声明所有接口的方法。

Generally, you mock a class and only declare certain methods in ->setMethods() . 通常,您模拟一个类,只在->setMethods()声明某些方法。 The un-mocked methods fall back to the implementations on the original class being mocked. 未经模拟的方法可以回溯到被模拟的原始类的实现。

But if you are mocking an interface, all methods must be implemented by the mock. 但是如果你在模拟一个接口,那么所有方法都必须由mock实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM