Search code examples
iosswiftxctestxctestcase

weak variable is becoming nil while writing testcase?


Hi I am writing a testcase for a function in ViewModel in where I am using a weak variable,

While testing the function , the weak variable is becoming nil , also I instantiated it and provided value to that object just before calling the testing function. Why is it becoming nil , and then how do i test it!!!

ALSO I cannot make weak variable strong type!!, working on others code

Compiler Warning - Instance will be immediately deallocated because property 'source' is 'weak'

CODE

func testFundTrip() {
     viewModel.source = SourceViewTypeMock()
     viewModel.fundTrip(trip)
}

In ViewModel

func fundTrip(_ trip: TravelTrip) {
        if let source = source { 
          // Here source is becoming nil ?? why 
        }
    }

Is there something with testcases methods with scopes of variables ?


Solution

  • The warning is telling you exactly what's happening. You only have a weak pointer to a value, so nothing is going to keep your SourceViewTypeMock alive past the assignment statement. The solution is to create a strong reference. You need one that the compiler is not allowed to optimized out, so it has to be outside of this function. So you make it a property of the test case.

    If it's immutable, you can do it this way:

    class TheTestCase: XCTestCase {
        let sourceMock = SourceViewTypeMock()
    
        func testFundTrip() {
            viewModel.source = sourceMock
            viewModel.fundTrip(trip)
        }
    }
    

    If it's mutable, then you probably want to make sure you recreate it in setUp:

    class TheTestCase: XCTestCase {
        var sourceMock: SourceViewTypeMock!
    
        override func setUp() {
            sourceMock = SourceViewTypeMock()
        }
    
        func testFundTrip() {
            viewModel.source = sourceMock
            viewModel.fundTrip(trip)
        }
    }