TechHui

Hawaiʻi's Technology and New Media Community

Microsoft has come a long way when it comes to support for unit tests.  They basically co-opted NUnit as their basic building block for testing.  Of course they re-branded it as MSTest and added feature/bug tracking and some more stuff all bundled together into TFS.

Given their willingness to get that deep into the unit test craze, their choice of interfaces for ObjectContext (on the server side) and DataServiceContext (on the client side) seems a bit odd.  There is no interface to be mocked or even virtual methods that can be mocked.  This makes testing WCF Data Services clients without hitting the server feel impossible.  But, the spirit of the TDD'er cannot be crushed for long.

In this site, Pablo Cibraro has used a repository pattern to totally encapsulate the DataServiceContext functionality and only expose mock-able interfaces to his application.  This approach took me a long ways to where I needed to go in my current application but it was missing one use case.  In parts of my application, I need only a few of the attributes of one of my entities.  It was absolutely essential that I only query the fields that were required as the other fields contained a lot of data that we didn't want to push over the wire needlessly.  So I modified the repository to include this method:

public IQueryable<TReturn> Retrieve<TEntity,TReturn>(
    Expression<Func<TEntity,TReturn>> selector,
    Expression<Func<TEntity, bool>> predicate,
    string ordering = null)

This is similar to the other Retrieve methods but allows the caller to supply an expression that resolves to a list of entity properties that will be filled by the query.

The body of the method is pretty simple and follows the pattern of the other Retrieve methods:

var entitySet = ResolveEntitySet(typeof (TEntity));
var query = _context.CreateQuery<TEntity>(entitySet);
query = (DataServiceQuery<TEntity>)query.Where(predicate);  //add the predicate
if (!string.IsNullOrEmpty(ordering)) {                       
  query = query.AddQueryOption("$orderby", ordering);            //add ordering, if provided
}
return query.Select(selector);                                                //add selectors

I've added a couple of other methods for dealing with paging but that will have to wait for another post.

Keep testing!!

Views: 663

Comment

You need to be a member of TechHui to add comments!

Join TechHui

Sponsors

web design, web development, localization

© 2014   Created by Daniel Leuck.

Badges  |  Report an Issue  |  Terms of Service