Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中使用-testing和pytest模拟abastract类或接口_Python_Unit Testing_Testing_Pytest_Testunit - Fatal编程技术网

如何在Python中使用-testing和pytest模拟abastract类或接口

如何在Python中使用-testing和pytest模拟abastract类或接口,python,unit-testing,testing,pytest,testunit,Python,Unit Testing,Testing,Pytest,Testunit,我创建一个界面,为我的控制器提供电子邮件验证 class EmailValidatorInterface(ABC): """ Interface to EmailValidator use case """ @abstractmethod def is_valid(self, email: str) -> bool: """ Specific case &qu

我创建一个界面,为我的控制器提供电子邮件验证

class EmailValidatorInterface(ABC):
    """ Interface to EmailValidator use case """

    @abstractmethod
    def is_valid(self, email: str) -> bool:
        """ Specific case """

        raise Exception("Should implement method: is_valid")
这是我的控制器实现

class SignUpController(RouteInterface):
    def __init__(self, emailValidator: EmailValidatorInterface):
        self.emailValidator = emailValidator

    def route(self, http_request: Type[HttpRequest]) -> HttpResponse:
如何为我的EmailValidator创建模拟? 我正在尝试使用mock.patch,但不知道如何初始化mock

看看我的测验

def test_should_return_400_if_invalid_param_is_provided():

    with mock.patch('EmailValidatorStub') as MockEmailValidator:
        MockEmailValidator.return_value.is_valid.return_value = False

    sut = SignUpController(EmailValidatorStub())
    attributes = {
        "name": faker.word(),
        "login": faker.word(),
        "email": "any_email",
        "email_confirmation": "any_email@mail.com",
        "password": "any_password",
        "password_confirmation": "any_password"
    }

    request = HttpRequest(body=attributes)
    httpResponse = sut.route(request)
    assert httpResponse.status_code == 500




我认为这里不需要
mock.patch
,因为您可以使用依赖注入。换句话说,只需像平常一样创建一个子类,但添加特定于测试的实现:

class MockValidator(EmailValidatorInterface):
   pass
然后在测试中实例化它:

sut = MockValidator()

您可以为正在测试的每个场景创建一个单独的模拟类,也可以添加一个
\uuuu init\uuu()
方法,该方法接受每个场景中可能不同的参数。或者两者的某种结合。mock不应该包含任何逻辑,而应该只满足测试的特定场景。

Hi,这很有意义。我可以创建一个存根类EmailValidatorStub(EmailValidatorInterface):我关心它,为了解决多个场景…我会在这个存根类中添加逻辑,因为在某些场景中它应该返回true,在某些情况下,它应该返回false。是这样吗?我是说,在存根类中添加逻辑?我正试图用一种干净的架构方法来完成这个项目。好的,我知道我还可以创建一个或两个以上的存根类来支持该场景……如果这是一个好的实践,我就不知道了。@user428745 mock应该有最小的逻辑。这里的第三个选项是为给定测试的场景将值传递到
\uuuu init\uuuu()