Unit tests that involves URLSession with background configuration

Hi guys,

I've been working on a framework that allows uploading a file to a given location. Everything works fine as expected if I run the sample app and manually test this feature, but unit tests for it always fail. Have you ever encountered a similar problem? Is it ever possible to use URLSession with background configuration in XCTest target? I will appreciate any feedback, here's the error message I get when executing a unit test. Note that I put ### for URL keys since it's sensitive data:

failed to create a background NSURLSessionUploadTask, as remote session is unavailable

2023-02-27 11:08:43.082279+0100 xctest[6870:4862390] Task <624B2B68-4A97-4180-A0F8-38AF9ECBC1B7>.<1> finished with error [-1] Error Domain=NSURLErrorDomain Code=-1 "nieznany błąd" UserInfo={NSErrorFailingURLStringKey=###, NSErrorFailingURLKey=###, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "BackgroundUploadTask <624B2B68-4A97-4180-A0F8-38AF9ECBC1B7>.<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=BackgroundUploadTask <624B2B68-4A97-4180-A0F8-38AF9ECBC1B7>.<1>, NSLocalizedDescription=nieznany błąd}

I don’t think there’s any reasonable way to use URLSession background sessions in a unit test. Ignoring the specific error you’re seeing for the moment, I can see at least two big picture issues:

  • Testing background sessions requires that the system be able to send you session events via the app delegate, and unit tests don’t let you see those events.

  • Even if that weren’t the case, a unit test is meant to run quickly and background sessions can introduce arbitrary delays.

My recommendation is that you add a feature to your framework to run requests in a standard session. This might just be for testing, but you might also consider making it part of the framework’s API because such things are often useful in other cases, for example, someone using your framework in a Mac product [1].

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] macOS supports background sessions but in most cases they’re not necessary because macOS has much fewer limitations around background execution.

I just made it possible to provide a standard URLSession object that also solves the problem with unit tests. Thank you for your feedback!

Unit tests that involves URLSession with background configuration
 
 
Q