title: How To Properly Unit-Test CRUD Operations on a Repository?
body: <p>Realize this may sound like a broad question - so let me clarify. I have a Repository exposed via an interface, with two concrete implementations - a <strong>MockRepository</strong> and a <strong>EntityFrameworkRepository</strong>.</p>
  
  <p>Now, i have a Unit-Test project for which all tests can be run against <em>either</em> repository, via flicking over a line in <code>[TestInitialize]</code>.</p>
  
  <p>My question is basically "How should i write the tests".</p>
  
  <p>Here's what i have:</p>
  
  <p><strong>C</strong> reate</p>
  
  <pre><code>// Arrange.
  var foo = new Foo { .. };
  
  // Act
  Repository.Add(foo);
  UnitOfWork.Commit();
  
  // Assert
  Assert.IsTrue(foo.Id &gt; 0);
  </code></pre>
  
  <p><strong>R</strong> etrieve</p>
  
  <pre><code>// Arrange.
  var fooToGet = 1;
  
  // Act
  var foo = Repository.FindSingle(fooToGet);
  
  // Assert
  Assert.IsNotNull(foo);
  Assert.AreEqual(foo.Id, fooToGet);
  </code></pre>
  
  <p><strong>U</strong> pdate</p>
  
  <pre><code>// Arrange.
  var fooToGet = 1;
  var nameToChangeFooTo = "FooBar";
  
  // Act
  var foo = Repository.FindSingle(fooToGet);
  foo.Name = nameToChangeFooTo;
  UnitOfWork.Commit();
  var fooRetrievedAgain = Repository.FindSingle(fooToGet);
  
  // Assert
  Assert.IsNotNull(foo);
  Assert.AreEqual(fooRetrievedAgain.Id, fooToGet);
  Assert.AreEqual(fooRetrievedAgain.Name, nameToChangeFooTo);
  </code></pre>
  
  <p><strong>D</strong> elete</p>
  
  <pre><code>// Arrange.
  var fooToGet = 1;
  
  // Act
  var foo = Repository.FindSingle(fooToGet);
  Repository.Remove(foo);
  UnitOfWork.Commit();
  var fooRetrievedAgain = Repository.FindSingle(fooToGet);
  
  // Assert
  Assert.IsNull(fooRetrievedAgain);
  </code></pre>
  
  <p>It's working <strong>ok</strong>, for both the Mock and EF repository, but my main problem is C (Create). I'm not sure how to test an Add operation on my Repository. It doesn't <em>feel right</em> what im doing.</p>
  
  <p>It passes for the EF Repository, but to make it pass in my Mock Repository i had to use reflection to update the ID in the in-memory collection (nasty).</p>
  
  <p>So - can you please share some advice on what are the correct ways to test CRUD operations on the Repository Pattern?</p>
  
  <p>This is an ASP.NET MVC Application, .NET 4, C#, Entity Framework 4 and Unit of Work/Repository Patterns.</p>
  
  <p>Thanks.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Just to clarify guys, these are not <strong>all</strong> the unit-tests i have. I have unit tests for my service layer, as well as business-rule tests.</p>
  
  <p>Both the latter will (and should) fail if my above Repository tests fail. That is the point here, to unit-test the <em>very basic operations</em> of my Repositories. Am i wrong?</p>