0

My view model is as such:

public class MainTabBarViewModel: MainTabBarInputs {
    unowned var output: MainTabBarOutputs
    ...
}

where the view controller is this:

class ViewController: MainTabBarOutputs {
    var viewModel: MainTabBarInputs!
}

I'm trying to write a unit test to test for the retain cycle:

class MainTabBarViewModelTests: XCTestCase {

    var viewModel: MainTabBarViewModel!
    var viewController: MockMainTabBarViewController!

    func testRetainViewController() {
        viewController = nil
        // TODO how do you test this
        expect(self.viewModel.output).to(beNil())
        // crashes because I can't 
        // reference an unowned pointer that's deallocated.
    }

I know if I changed my reference to be weak I could test this, but what if I wanted to leave it as unowned?

Huy-Anh Hoang
  • 777
  • 6
  • 24
  • Related: https://stackoverflow.com/questions/54836745/does-arc-hold-a-count-for-unowned-reference – Cristik Oct 01 '19 at 18:28

1 Answers1

1

You can use a weak reference to the controller in the unit test, and if that reference becomes nil, then you don't have a retain cycle:

func testRetainViewController() {
    weak var testRef = viewController
    viewController = nil
    expect(testRef).to(beNil())
}

You can easily validate the above approach by changing from unowned to strong and see that the test fails.

Cristik
  • 30,989
  • 25
  • 91
  • 127