How to write a unit test which will pass if another function was triggered in Swift

Viewed 17

So i have a simple user validation function and i want to write unit test about it. I want it to pass only when it's triggering another function, how can i write this logic?

Here is the function

func validateUser(request: Login.UserValidation.Request) {
    // unwrapping email and password above this
    if email == "" || password == "" {
        presenter?.presentUserValidationOutcome(response: response)
    }

Here is the unit test i want to write

func test_validateUserFailure() {
    // Given
    let email = "test"
    let password = ""

     // When
     sut.validateUser(request: Login.UserValidation.Request(email: email, password: password))
        
     // Then
     // check if it triggered presenter's function
    }
1 Answers

Found an answer. The thing is to mock the class conforming the protocol, which protocol is conforming the class where our target function is. After doing that we can check if the function was triggered by using variable for example loginWasCalled = true and then in unit test when checking if it is true we must cast the presenter as the mocked one in this case as a MockedLoginPresenter. Here is the code example

Mocked class:

class MockedLoginPresenter {
    var presenterWasCalled = false
}

extension MockedLoginPresenter: LoginPresentationLogic {
    func presentUserValidationOutcome(response: MentalHealthApp.Login.UserValidation.Response) {
        presenterWasCalled = true
    }
}

Unit test:

func test_validateUserFailure() {
    // Given
    let email = "test"
    let password = ""
    
    // When
    sut.validateUser(request: Login.UserValidation.Request(email: email, password: password))
    
    // Then
    XCTAssertTrue((sut.presenter as! MockedLoginPresenter).presenterWasCalled, "Both fields are filled therefore it will first call loginUser function before triggering the presenter function")
}
Related