My app uses CoreData. One of the entities is
final class ViewItem: NSManagedObject {
// …
}
During unit tests, I am trying to execute the following fetch request:
let viewItemFetchRequest = NSFetchRequest<ViewItem>(entityName: "ViewItem")
as
viewContext.performAndWait {
do {
let fetchedViewItems = try viewContext.fetch(viewItemsFetchRequest)
let viewItems = Set(fetchedViewItems)
// …
}
Although the code executes correctly during normal operation, during unit tests it crashes.
When I set a breakpoint behind the try
instruction, this breakpoint is reached, i.e. the fetch does not throw.
However I get a fatal error when I want to access fetchedViewItems
, either by Set(fetchedViewItems)
or with
(lldb) po fetchedViewItems
Fatal error: NSArray element failed to match the Swift Array Element type
Expected ViewItem but found ViewItem
2022-06-07 10:31:30.245019 0200 ShopEasy[42069:1864673] Fatal error: NSArray element failed to match the Swift Array Element type
Expected ViewItem but found ViewItem
1 value
Here is the relevant part of the stack frame:
What could be the reason and how could I fix the problem?
PS: I found some posts related to this error,
The code should only be present in your app target, and you should use @testable import ShopEasy
to access app code in your unit tests.