title: iOS Application Unit Testing with Core Data, and Magical Record
body: <p>I have an iOS app that uses Core Data along with the excellent <a href="https://github.com/magicalpanda/MagicalRecord" rel="nofollow noreferrer">Magical Record</a> to manage persistence. Here is my problem:</p>
  
  <p>Our existing Unit Testing structure uses the standard iOS application tests. I want to run my unit tests with a clean in-memory db for each test. I followed the directions in <a href="http://www.cimgf.com/2012/05/15/unit-testing-with-core-data/" rel="nofollow noreferrer">this article</a> to set that up using Magical Record. The issue comes up in the implementation of running application tests. Because application tests run the application bundle first, then the unit test bundle, my normal call to set up the core data stack is being called before my in-memory store call has a chance to run. </p>
  
  <p>I googled this issue all night, and found a couple of promising articles:</p>
  
  <ul>
  <li><a href="http://blog.goosoftware.co.uk//2013/02/07/unit-testing-a-coredata-manager-class/" rel="nofollow noreferrer">http://blog.goosoftware.co.uk//2013/02/07/unit-testing-a-coredata-manager-class/</a></li>
  <li><a href="https://stackoverflow.com/questions/6880739/how-to-use-core-data-for-dependency-injection">How to use Core Data for Dependency Injection </a></li>
  </ul>
  
  <p>The problem with these is that they are using a singleton data access object as a gateway into their core data calls. My app is not set up this way. I am using calls into Magical Record to do my data fetching and saving.</p>
  
  <p>Has anyone run into this issue? If so, am I missing some detail that would allow me to swap out my data setup to an in-memory store when my tests are running? </p>
  
  <p><strong>EDIT: Adding code</strong></p>
  
  <p>In my app delegate, I have this:</p>
  
  <pre><code>-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
      [MagicalRecord setupAutoMigratingCoreDataStack];
      // Other setup code
      return YES;
  }
  </code></pre>
  
  <p>In every unit test class that deals with core data, I have this:</p>
  
  <pre><code>-(void)setUp{
      [super setUp];
      [MagicalRecord setDefaultModelFromClass:[self class]];
      [MagicalRecord setupCoreDataStackWithInMemoryStore];
  }
  
  -(void)tearDown{
      [MagicalRecord cleanUp];
      [super tearDown];
  }
  </code></pre>
  
  <p>I can see that both the app delegate code and setup/teardown are called for each test, but I'm not sure how to make the default core data stack for the tests use the in memory store. I also have the .xcdatamodel file added to the unit test target.</p>