Unit Testing – Assert Current Thread is Main Thread in iOS

Architectureiosmultithreadingobject-oriented-designunit testing

The question is does it make sense to write a unit test which asserts that the current thread is the main thread? Pros/cons?

Recently I've seen the unit test which asserts the current thread for the callback of service. I'm not sure, that it's a good idea, I believe it's more kind of integration test. In my opinion, the unit test should assert method in isolation and should not know about the nature of the consumer of service.

For example, in the iOS, the consumer of this service is intended to be a UI which by default has a constraint to run a code at the main thread.

Best Answer

Let me show you my favorite unit test principles:

A test is not a unit test if:

  1. It talks to the database
  2. It communicates across the network
  3. It touches the file system
  4. It can't run at the same time as any of your other unit tests
  5. You have to do special things to your environment (such as editing config files) to run it.

A Set of Unit Testing Rules - Michael Feathers

If your unit test insists that it be the "main thread" it's hard not to run afoul of number 4.

This may seem harsh but remember that a unit test is just one of many different kinds of tests.

enter image description here

You're free to violate these principles. But when you do, don't call your test a unit test. Don't put it with the real unit tests and slow them down.

Related Topic