5

We can make @IBOutlets and @IBAction private. Example:

class MyViewController: UIViewController {

    @IBOutlet private weak var myLabel: UILabel!

    @IBAction private func nextTapped(sender: UIButton) {
        // Do something
    }

}

We haven't access to this properties and methods outside class, which is good I thing.

But what about testing class with private outlets and actions? Are there any ways to test private outlet or method in XCTestCase, or I have to just expose them outside class making internal?

For purpose of test @IBOutlets/@IBActions should be internally visible?

Daniel Sumara
  • 2,234
  • 20
  • 25
  • Possible duplicate of [Swift - Unit testing private variables and methods](http://stackoverflow.com/questions/37421235/swift-unit-testing-private-variables-and-methods) – Fantattitude Oct 05 '16 at 08:01

3 Answers3

7

There is no way to test private methods with XCTest.

That's because Swift's private is really private and the compiler uses this information to make better optimizations of your code.

To test a method it either must be public or internal and you can import your module with @testable.

Excerpt from Should I test private methods or only public ones? :

I do not unit test private methods. A private method is an implementation detail that should be hidden to the users of the class. Testing private methods breaks encapsulation.

Community
  • 1
  • 1
Fantattitude
  • 1,842
  • 2
  • 18
  • 34
0

Use private(set) for the IBOutlets. So you can read it outside the class but cannot modify it.

NuN
  • 408
  • 4
  • 13
-1

Private methods MUST be tested also, but the point is not change anything in the class under test for running the tests.

By default you can access to IBOutlets from unit tests, but in case you have set them as private you can always create a new MockSubclass of your class under test and then expose the private stuff.

During the test just instantiate your mock subclass and call a function that returns your private outlet.

Look out! keep your mock classes always under test target.