1

I'm trying to write the tests for a project I've been working on and I can't seem to figure out how to test some of my methods. So, some of the methods modify a private property (Array) by adding or removing items to the array. How can I test this cases?

Thanks!

2 Answers 2

1

Basically you are asking how to test a private property.

NOTE: This approach only works against Framework targets

If your class inherit from NSObject you should check here: http://saulmora.com/2015/01/15/unit-testing-in-swift-without-access-levels.html

Sign up to request clarification or add additional context in comments.

Comments

1

How about opening up your private properties and methods in an extension and only use that for testing. Remove the extension (comment it out) when not testing.

Here I put a 'T' in front of the private method or property name in the extension.

For example:

class MyClass {
  private var privateString: String?

  private func privateSetName(name: String) {

    privateString = name
  }

extension MyClass {  // for testing only

  var TprivateString: String? {
    get {
      return self.privateString
    }
  }

  func TprivateSetName(name: String) {
    privateSetName(name)
  }
}

then in your XCTest you can do:

func testThatNameIsSet() {

  let myClass = MyClass()

  myClass.TprivateSetName("myName")

  XCTAsserNotNil(myClass.TprivateString, "Name should be set.") 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.