Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6219837
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T07:51:12+00:00 2026-05-24T07:51:12+00:00

I’m toying with using Core Data to manage a graph of objects, mainly for

  • 0

I’m toying with using Core Data to manage a graph of objects, mainly for dependency injection (a subset of the NSManagedObjects do need to be persisted, but that isn’t the focus of my question). When running unit tests, I want to take over creation of the NSManagedObjects, replacing them with mocks.

I do have a candidate means of doing this for now, which is to use the runtime’s method_exchangeImplementations to exchange [NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:] with my own implementation (ie. returning mocks). This works for a small test I’ve done.

I have two questions regarding this:

  1. is there a better way to replace Core Data’s object creation than swizzling insertNewObjectForEntityForName:inManagedObjectContext? I haven’t forayed far into the runtime or Core Data, and may be missing something obvious.
  2. my replacement object creation method concept is to return mocked NSManagedObjects. I’m using OCMock, which won’t directly mock NSManagedObject subclasses because of their dynamic @propertys. For now my NSManagedObject’s clients are talking to protocols rather than concrete objects, so I return mocked protocols rather than concrete objects. Is there a better way?

Here’s some pseudoish code to illustrate what I’m getting at. Here’s a class I might be testing:

@interface ClassUnderTest : NSObject 
- (id) initWithAnObject:(Thingy *)anObject anotherObject:(Thingo *)anotherObject;
@end


@interface ClassUnderTest()
@property (strong, nonatomic, readonly) Thingy *myThingy;
@property (strong, nonatomic, readonly) Thingo *myThingo;
@end

@implementation ClassUnderTest
@synthesize myThingy = _myThingy, myThingo = _myThingo;
- (id) initWithAnObject:(Thingy *)anObject anotherObject:(Thingo *)anotherObject {

    if((self = [super init])) {
        _myThingy = anObject;
        _myThingo = anotherObject;
    }

    return self;
}
@end

I decide to make Thingy and Thingo NSManagedObject subclasses, perhaps for persistence etc, but also so I can replace the init with something like:

@interface ClassUnderTest : NSObject 
- (id) initWithManageObjectContext:(NSManagedObjectContext *)context;
@end

@implementation ClassUnderTest
@synthesize myThingy = managedObjectContext= _managedObjectContext, _myThingy, myThingo = _myThingo;
- (id) initWithManageObjectContext:(NSManagedObjectContext *)context {

    if((self = [super init])) {
        _managedObjectContext = context;
        _myThingy = [NSEntityDescription insertNewObjectForEntityForName:@"Thingy" inManagedObjectContext:context];
        _myThingo = [NSEntityDescription insertNewObjectForEntityForName:@"Thingo" inManagedObjectContext:context];
    }

    return self;
}
@end

Then in my unit tests I can do something like:

- (void)setUp {
    Class entityDescrClass = [NSEntityDescription class];
    Method originalMethod = class_getClassMethod(entityDescrClass,  @selector(insertNewObjectForEntityForName:inManagedObjectContext:));
    Method newMethod = class_getClassMethod([FakeEntityDescription class],  @selector(insertNewObjectForEntityForName:inManagedObjectContext:));
    method_exchangeImplementations(originalMethod, newMethod);

}

… where my []FakeEntityDescription insertNewObjectForEntityForName:inManagedObjectContext] returns mocks in place of real NSManagedObjects (or protocols they implement). The only purpose of these mocks is to verify calls made to them while unit-testing ClassUnderTest. All return values will be stubbed (including any getters referring to other NSManagedObjects).

My test ClassUnderTest instances will be created within the unit tests thus:

ClassUnderTest *testObject = [ClassUnderTest initWithManagedObjectContext:mockContext];

(the context won’t actually be used in test, because of my swizzled insertNewObjectForEntityForName:inManagedObjectContext)

The point of all this? I’m going to be using Core Data for many of the classes anyway, so I might as well use it to help reduce the burden managing changes in constructors (every constructor change involves editing all clients including a bunch of unit tests). If I wasn’t using Core Data, I might consider something like Objection.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T07:51:14+00:00Added an answer on May 24, 2026 at 7:51 am

    Looking at your sample code, it seems to me your test is getting bogged down in the details of the Core Data API, and as a result the test isn’t easy to decipher. All you care about is that a CD object was created. What I’d recommend is abstracting away the CD details. A few ideas:

    1) Create instance methods in ClassUnderTest that wrap the creation of your CD objects, and mock them:

    ClassUnderTest *thingyMaker = [ClassUnderTest alloc];
    id mockThingyMaker = [OCMockObject partialMockForObject:thingyMaker];
    [[[mockThingyMaker expect] andReturn:mockThingy] createThingy];
    
    thingyMaker = [thingyMaker initWithContext:nil];
    
    assertThat([thingyMaker thingy], sameInstance(mockThingy));
    

    2) Create a convenience method in ClassUnderTest’s superclass, like -(NSManagedObject *)createManagedObjectOfType:(NSString *)type inContext:(NSManagedObjectContext *)context;. Then you can mock calls to that method using a partial mock:

    ClassUnderTest *thingyMaker = [ClassUnderTest alloc];
    id mockThingyMaker = [OCMockObject partialMockForObject:thingyMaker];
    [[[mockThingyMaker expect] andReturn:mockThingy] createManagedObjectOfType:@"Thingy" inContext:[OCMArg any]];
    
    thingyMaker = [thingyMaker initWithContext:nil];
    
    assertThat([thingyMaker thingy], sameInstance(mockThingy));
    

    3) Create a helper class that handles common CD tasks, and mock the calls to that class. I use a class like this in some of my projects:

    @interface CoreDataHelper : NSObject {}
    
    +(NSArray *)findManagedObjectsOfType:(NSString *)type inContext:(NSManagedObjectContext *)context;
    +(NSArray *)findManagedObjectsOfType:(NSString *)type inContext:(NSManagedObjectContext *)context usingPredicate:(NSPredicate *)predicate;
    +(NSArray *)findManagedObjectsOfType:(NSString *)type inContext:(NSManagedObjectContext *)context usingPredicate:(NSPredicate *)predicate sortedBy:(NSArray *)sortDescriptors;
    +(NSArray *)findManagedObjectsOfType:(NSString *)type inContext:(NSManagedObjectContext *)context usingPredicate:(NSPredicate *)predicate sortedBy:(NSArray *)sortDescriptors limit:(int)limit;
    +(NSManagedObject *)findManagedObjectByID:(NSString *)objectID inContext:(NSManagedObjectContext *)context;
    +(NSString *)coreDataIDForManagedObject:(NSManagedObject *)object;
    +(NSManagedObject *)createManagedObjectOfType:(NSString *)type inContext:(NSManagedObjectContext *)context;    
    
    @end
    

    These are trickier to mock, but you can check out my blog post on mocking class methods for a relatively straightforward approach.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have thousands of HTML files to process using Groovy/Java and I need to
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I need to clean up various Word 'smart' characters in user input, including but
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.