OlivierTo
OlivierTo

Reputation: 253

iOS unit test with core data/MagicalRecord unexpected behavior

I got the following test code.

@interface SubscriberTest : XCTestCase

@end

@implementation SubscriberTest

- (void)setUp
{
    [super setUp];
    [MagicalRecord setDefaultModelFromClass:[self class]];
    [MagicalRecord setupCoreDataStackWithInMemoryStore];

}


- (void)tearDown
{
    [super tearDown];
    [MagicalRecord cleanUp];
}

- (void)testParseSubscriberWithEvents
{
   NSEntityDescription *pDesc = [NSEntityDescription entityForName:@"Subscriber"
                                         inManagedObjectContext:[NSManagedObjectContext MR_defaultContext]];
   XCTAssertNotNil(pDesc);


- (void)testParseSubscriberWithReviews
{
   NSEntityDescription *pDesc = [NSEntityDescription entityForName:@"Subscriber"
                                         inManagedObjectContext:[NSManagedObjectContext MR_defaultContext]];
    XCTAssertNotNil(pDesc);

}

@end

I don't understand why the first test always succeed and the second always fail.. it's like each test is creating is own ManagedObjectContext, but the second is not aware of my entity... In fact this code is used to test import of json data. I debugged MagicalRecord's code to see that the problem comes from the method

[NSEntityDescription entityForName: inManagedObjectContext:]

Which is returning nil in the second test...

I tried to comment the first test, the second test worked! but if they are two test the second fails each time...

For info i'm using MagicalRecord 2.3.0.beta (because of some bugs in 2.2 importFromObject method...) Any help and explanation would be much appreciated!

Upvotes: 2

Views: 421

Answers (1)

Digitech
Digitech

Reputation: 292

Looks like after the first test -tearDown destroys CoreData stack, for some reason next time -setUp is called MagicalRecord doesn't correctly initialize Core Data stack (second time context is nil as you found) which results in failing your second test. I found that if you setup core data stack once (you can achieve this by calling dispatch_once in -setUp) and call [Subscriber MR_truncateAll] in -tearDown it does work.

Upvotes: 1

Related Questions