Reputation: 853
I create an interface to provide email validation for my controller
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")
That is my controller implementation
class SignUpController(RouteInterface):
def __init__(self, emailValidator: EmailValidatorInterface):
self.emailValidator = emailValidator
def route(self, http_request: Type[HttpRequest]) -> HttpResponse:
How can I create a mock for my EmailValidator? I'm trying to use mock.patch but I don't how to initialize the mock
Look at my test
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": "[email protected]",
"password": "any_password",
"password_confirmation": "any_password"
}
request = HttpRequest(body=attributes)
httpResponse = sut.route(request)
assert httpResponse.status_code == 500
Upvotes: 2
Views: 2203
Reputation: 83557
I don't think you need mock.patch
here since you can just use dependency injection. In other words, just create a subclass like you normally would, but add implementation that is specific to the test:
class MockValidator(EmailValidatorInterface):
pass
Then instantiate it in your test:
sut = MockValidator()
You can either create a separate mock class for each scenario you are testing or add a __init__()
method that takes parameters that can vary between each scenario. Or some combination of the two. Mocks shouldn't contain any logic but instead just satisfy a specific scenario that is tested.
Upvotes: 4