0

I've begun testing my NSManagedObject subclasses, and I'm running into a problem with inconsistent results saving and fetching in one of the test cases.

My setup is pretty simple - for testing I have an in-memory persistent store. I hold on to a reference through the test.

On testing setup, I clear the persistent store:

- (void)setUp {
    [super setUp];

    if(!self.manager){
        self.manager = [DataManager inMemoryManager];
    }
    [self.manager.managedObjectContext reset];
}

The test case is simple: 1. read data from a JSON file, parse and configure my objects 2. Save 3. Create a fetch request on the object's external ID (should only be one)

When running the test case by itself (or just that test Class), I get 1 result, as expected. However, running ALL unit tests and classes, it produces 3 results from the fetch. Sometimes the relationships are fine (passing) and other times they fail (no relationship).

Since I am resetting the context each time on setup, I should have a blank slate for each test, shouldn't I?

Instead, I think I'm getting leftovers from another test case polluting my data sample, but have no idea how to go about fixing it.


In case you're interested in the fetched results:

<__NSArrayM 0x7f9b2842c650>(
<MyObject: 0x7f9b28435430> (entity: MyObject; id: 0x7f9b28440370 <x-coredata://9CE4448C-6595-47FC-A189-58A83F708D96/MyObject/p11> ; data: {
    externalID = 222abc;
    theChildren =     (
        "0x7f9b2843f020 <x-coredata://9CE4448C-6595-47FC-A189-58A83F708D96/ChildObject/p9>",
        "0x7f9b2843fec0 <x-coredata://9CE4448C-6595-47FC-A189-58A83F708D96/ChildObject/p12>"
    );
}),
< MyObject: 0x7f9b28440c00> (entity: MyObject; id: 0x7f9b28731890 <x-coredata://9CE4448C-6595-47FC-A189-58A83F708D96/MyObject/p5> ; data: <fault>),
< MyObject: 0x7f9b28440c60> (entity: MyObject; id: 0x7f9b28729490 <x-coredata://9CE4448C-6595-47FC-A189-58A83F708D96/MyObject/p3> ; data: <fault>)
)
Cameron
  • 1,142
  • 8
  • 32

1 Answers1

0

setUp is only called once per test suite, you'd need to call reset before each test. I'd recommend switching to Specta and using it's beforeEach to reset. ( example - though not with a managed object contest )

orta
  • 4,225
  • 1
  • 26
  • 34
  • I thought that might be it, but found this explanation. http://stackoverflow.com/a/21040654/694080 – Cameron Oct 15 '14 at 05:13
  • Even when running the clear on setup AND teardown, I still run into issues. I've also tried clearing before and after in each test case with no fix. If I comment-out other tests that make use of `[context save:&error]` (in some other test classes) it seems to be fine. What does seem to help is making my inMemoryManager NOT be a singleton, so each test gets its own instance (for better or for worse). Doesn't seem sound, but is it acceptable for a case like this? – Cameron Oct 15 '14 at 05:20
  • Why was it a singleton in the first place? – quellish Oct 16 '14 at 05:36