Continuation of Protocols…
This is a continuation of previous article
Scenario 2:
As we all have worked on SignIn or SignUp Process, Have done Network calls and Parsed responses. Let’s talk about Validator for now.
Note: By The way 2nd and 3rd points of This are linked I’ll let you know why.
As making request for login we first validate fields and for that we usually add if else in Action, But that cannot be get Tested(writing test cases) any way. So here is a Concept Single Responsibility ‘S’ from SOLID. Controller is not responsible of validating any fields. So we’ll make a Separate class for that. And distribute the responsibility.
Let start the coding part
protocol ValidatorType{
func isValid() -> Bool
}// Class Implementing typeclass EmailValidator: ValidatorType{ var value: String? init(value: String){ self.value = value } func isValid() -> Bool {// add condition
return true }
}
Now lets create a Unit test for it,
Now in this way any Field, The benefit is that you can create testcase for the function.class MockValidator: ValidatorType{var value: String? = abcfunc isValid() -> Bool {
guard let value = value else {
return false
}
return value == "abc"
}
}// Testcase for success Scenario
func test_whenMockStringPassed_shouldReturnTrue() { let expectation = self.expectation(description: "Should return True")
var expectedValue = "abc" XCTAssertEqual(validateField(type: MockValidator(value: expectedValue)), true)
expectation.fulfill()}
This was a small demo of benefit of protocol and use case of Unit test. There are multiple Articles on Validators you can check, And I will also write a simple article for validator soon.
You can try in Many ways. I have also worked with Network classes which will be in Next Article.