Home > Enterprise >  How to set starting point for XCTest in xcode
How to set starting point for XCTest in xcode

Time:08-31

I try to be used to use XCTest on Xcode.

but my company app that is gonna be tested, has to receive token or userInfo or some datas from server first for calling functions.

So, it is quite hard to insert unit test because unit test codes are executed before getting token from server.

Is it possible to set test code's beginning point in sources that is gonna be tested? and to begin XCTest sources after specific viewController appear?

I found a way that inserting "DispatchQueue.global().asyncAfter", but it is not proper solution I think.

Thanks.

CodePudding user response:

I think the solution to your problem is called "dependency injection". You should google it. It is used in all object-oriented languages and has nothing to do with Swift or Xcode in particular.

Basically it means that you inject classes that you don't want to test - like in your case some kind of network interface - into the class that you want to test. In your production code you will inject the actual classes you need to communicate with your server or whatever and in your unit tests you will inject some kind of fake/stub/mock object(s) instead that pretend to behave like the actual class but really only do whatever you need to run your unit test. For example, when the class you want to test requests a token from the server, instead of actually making the request the fake network interface would simply return a hard coded toke value. This is the proper way to write unit tests. However, if writing unit tests was not taken into account when the architecture of your code was designed, this usually means a major refactoring of your code will be inevitable.

You may find these links useful:

  • Related