Reputation: 417
I am testing my UiViewController
s with XCUnitTests.
Sometimes I have to mock the UIViewController
in order to capture a method call. For example whether performSegue
has been called.
Sometimes one of the methods I test (like viewDidLoad
) access an IBOutlet. When I create a custom mock subclass and then say mockViewController.textfield = UITextField()
everything works great.
However, when I want to manually instantiate a UIView
or a UIStackView
the variable is still nil, even though the initializer of a UIView
can never return nil. Why?
Maybe this has something to do with UIView
s and UIStackView
s to not have an intrinsic content size? How do I fix this?
Upvotes: 0
Views: 402
Reputation: 417
Just after posting this question I already found the answer.
The reason why my manually instantiated view disappears is that my @IBOutlet
is a weak var
. Weak
simply means, that the variable itself can not keep the instance alive. You need some other variable to keep the instance alive. In my case instead of doing
mockViewController.stackView = UIStackView()
I do
let stackView = UIStackView()
mockViewController.stackView = stackView
This way the variable stackView
can keep the instance alive.
Upvotes: 1