4

After reading this Testability and Entity Framework 4.0 article about 75 times yesterday, it is not clear to me what the author was trying to say. He seems to indicate that UoW and Repository patterns are two different patterns to use to solve similar problems. In other words, UoW was more for multi objects that need to be orchestrated prior to commit, whereas Repository is for more straightforward persistence.

When I do more searching online to find the holy grail framework to allow me to unit test my application, I see more articles that seem to imply that UoW is part of the Repository pattern, or vice versa.

Which interpretation is correct?

At the end of the day I want to be able to isolate my application enough to allow mocking of the data to in memory objects.

6
  • Don't mock the data into memory objects, you WILL get burned. There are many many Linq queries that will work correctly against an in-memory store but will fail against EF4. You need to instead do integration tests against a real database if you want to be sure the queries your business logic asks for work correctly
    – KallDrexx
    Jul 13, 2011 at 17:07
  • But, I want to unit test separately from integration testing. So, I want to design in the chance that my queries will fail....I think. Jul 13, 2011 at 17:11
  • I'm going to write an answer instead of a comment because I feel like a comment doesn't give enough room to fully explain.
    – KallDrexx
    Jul 13, 2011 at 17:23
  • 1
    I don't agree with @KallDrexx. Being able to fake your LINQ provider in unit tests is really valuable (I do this all the time), because it allows you to test your business logic. I do agree however with him that it is no silver bullet. It does not completely remove the need to have integrations tests, because of the reasons he gave.
    – Steven
    Jul 13, 2011 at 17:55
  • 1
    Now I'm even more confused. I'll just dump my work and create the app in asp classic. At least then I'll have every expectation that my code will be duplicated, tightly coupled and completely untestable! :-) After all, it's only for filing tax returns. Jul 13, 2011 at 18:53

3 Answers 3

3

The problem you're running into is that people are misinterpreting the repository pattern.

The basic idea of the repository is that you should be able to treat your data like one big collection without worrying about what's behind it. This means that if you add an object to the collection you shouldn't have to worry about whether or not it's been saved. Hence Repositories should always persist on each action.

UnitOfWork on the other hand is used for coordinating multiple calls to the database that must be committed or rolled back together. The standard bank account transfer is an example of this. I don't want to persist changes to one bank account at a time since it would make it much harder to back out if I had problems with saving the second bank account.

In terms of testing either works. It's quite easy really (using Moq as an example)..

public void UpdateAddress()
{
   // Arrange
   User user = // Build your user somehow..
   myUnitOfWorkMock.Setup(x => x.Get<User>(It.IsAny<long>())).Returns(user);

   MyService sut = new MyService(myUnitOfWorkMock);

   // Act
   sut.ChangeAddress(userId, "1234 Copperhead Road");

   //Assert
   Assert.AreEqual("1234 Copperhead Road", user.Address);
}
4
  • 1
    Obviously I prefer UnitOfWork but if you were using a repository the same test logic would apply.. just applied differently. Jul 13, 2011 at 16:42
  • Can you look over your answer again? I was following along, but either I was reading it wrong or you have transposed some concepts. Jul 13, 2011 at 17:09
  • UnitOfWork on the other hand is used for handling multiple calls over a single unit of work.....Seems redundant and doesn't really explain anything. Jul 13, 2011 at 23:12
  • Ahhh yes.. I've changed it now. Jul 15, 2011 at 3:41
1

Be careful about following that advice in that page. I did and it didn't work out too well and I got burned a bit.

You NEED to test your business classes with integration tests (tests that involve a real database) instead of pure unit tests (using an in memory data store) instead of unit tests. The reason is that you will end up with your unit tests giving false passes AND false negatives.

Take the following example. Say your business logic wants to query for any requests that have been made as of today. In the business logic I would write:

var requests = _unitOfWork.Requests.Where(x => x.RequestDate.Date = DateTime.Now.Today).ToList();

This will work fine when run against in memory objects but this will trigger a NotImplementedException because EF can't effectively handle this type of query. There are a whole lot of Linq queries that are not supported by Entity Framework, but you won't catch them unless you are running integration tests. Thus your unit tests are now giving you false positives, they claim it works when it really doesn't.

Now take the case that your business logic wants to query for requests that were made by a specific user. Most likely your business logic to do this you will end up with a Linq statement such as:

var requests = _unitofWork.Requests.Where(x => x.UserId == userid).ToList();

The problem with this query is that in order to set the unit test up to pass you have to have knowledge of the implementation of the business logic. What I mean is this, if you have the following unit test for this:

[TestMethod]
public void Can_Retrieve_User_Requests()
{
    // Setup
    var user = new User();
    var req1 = new Request();       
    user.Requests.Add(req1);

    _unitOfWork.Add(user);
    _unitOfWork.Add(req1);
    _unitOfWork.Commit();

    // Act
    var result = BusinessLogicClass.GetRequestsByUserId(user.Id);

    // Assert
    Assert.IsNotNull(result);
    Assert.AreEqual(1, result.count);
}

This unit test works and will pass as is (all other aspects working of course) if the _unitOfWork is using your Entity Framework system.

If you are using an in memory unit of work this will fail for 2 reasons. The first is that user.Id isn't set, 99% of the time IDs will be generated by Entity Framework. Even if you explicitely set user.Id = X this will still fail, because you also need to set request.UserId. In EF, the request.UserId field will automatically be populated when a new relationship is created but this will not occur when using an in memory data set. This means that you have to explicitely know that GetRequestsByUserId() implements the query by looking at the Request.UserId field instead of Request.User.Id, and this also means that changing your unit test to pass in this instance will fail if you change your query to use Request.User.Id, even though the business logic and the result in EF is essentially the same.

One final example is what happens if your database field doesn't have enough room to store a long string (EF CodeFirst defaults db string lengths to be varchar(128)). If you have a test with more than 128 characters, your in memory data store will store the string just fine, but EF will exception because it's too long.

TLDR: In memory unit tests for data querying and data storage will not give you any confidence that your application is working correctly. You still have to create integration tests, but your integration tests will have to verify 99% of what your unit tests cover anyways, and thus it will double your TDD efforts, slow you down and make the tests harder to maintain.

Instead, integration tests with Sql Server Compact Edition will give you confirmation that not only does your business logic work correctly, it works correctly against a live database.

As a side note, I am talking about testing business logic using integration tests. Testing MVC controllers should only be done against a real database if the controllers actually access the database directly (which it shouldn't be imho, the MVC controllers should be calling on your business classes to perform DB operations), and if the controllers don't talk directly with the database then you can just use a mocking framework like Moq to do in memory mocks of your business classes (since they are already tested via the integration tests).

8
  • FYI, you don't have to mark this as an answer since I didn't actually answer your direct question, I just didn't think a comment was big enough to fully explain the issues with in memory testing
    – KallDrexx
    Jul 13, 2011 at 17:53
  • 1
    but - your tests here aren't 'unit testing' anything. you are simply asking for a case that your application may or may not actually do - such as: var requests = _unitOfWork.Requests.Where(x => x.RequestDate.Date = DateTime.Now.Today).ToList(); where is the 'unit' in this as opposes to testing some linq provider - code that isn't yours. Your unit tests should be testing portions of your code that are 'units' in your application - not potential cases. I think you may be crossing the two concepts a bit and blurring unit tests to include other non-unit type items. Jul 13, 2011 at 18:33
  • I'm not completely sure I understand you. You need to unit test that all cases that you ask your application to do actually work. If your business classes contain the Linq you mentioned, unit tests won't be enough to catch errors. If you abstract the Linq into a specific repository method, then you still need to integration test that method, but now you have a wasted layer of abstracted that will cause headaches down the road and much much more work for yourself
    – KallDrexx
    Jul 13, 2011 at 18:39
  • By specific repository method I am referring to using a non-generic repository (something his link isn't advocated) and instead doing var requests = _unitOfWork.Requests.GetTodaysRequests();
    – KallDrexx
    Jul 13, 2011 at 18:41
  • Wouldn't you be mocking var result = BusinessLogicClass.GetRequestsByUserId(user.Id); to return a particular object for that id? Jul 13, 2011 at 18:41
0

You can use them both separately or together. These posts that you cant use in memory objects - well - some would highly disagree without seeing a specific failing case.

Repository pattern dictates generally loading information - and if you so choose - saving information. From MSDN: "Use a repository to separate the logic that retrieves the data and maps it to the entity model from the business logic that acts on the model. T"

Load your data from your repository. Your unit of work pattern can surely encapsulate a transaction around all of your repository saves.

There is no reason you cannot use one, the other, or both together. Now - testing your objects depends on WHAT you want to test. IF you are testing a save to a store - then sure - this isn't a unit test. IF you want to mock your store and simply return an in memory object, then so be it. I think I'm missing why there is concern here from the other posters - call me blissfully ignorant.

Your unit tests are supposed to test a 'unit' not some potential call your app may or may not make. You want to test for ex. a method - not a linq provider

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.