1

I have started thinking about adding some unit tests around some business logic in my project.

The first method that I would like to test is a method in my service layer that returns a list of child nodes for a given node.

The method looks like this:

public List<Guid> GetSubGroupNodes(string rootNode)
{
    List<Tree> tree = ssdsContext.Trees.ToList();
    Tree root = ssdsContext.Trees.Where(x => x.UserId == new Guid(rootNode)).FirstOrDefault();
    return GetChildNodeIds(root, tree);
} 

private List<Tree> GetChildNodes(Tree rootNode, List<Tree> tree)
{
    kids.Add(rootNode);
    foreach (Tree t in FindChilden(rootNode, tree))
    {
        GetChildNodes(t, tree);
    }
     return kids;
}

The way I'd imaginge testing something like this is to provide a fake Tree structure and then test that a providing a node returns the correct subnodes.

ssdsContext is an ObjectContext.

I've seen that its possible to extract and interface for the ObjectContext How to mock ObjectContext or ObjectQuery<T> in Entity Framework? but I've also read that mocking a DBContext is a waste of time Unit Testing DbContext.

I have also read that as Entity Framework is an implementation of the repository pattern and unit of work patten here: Generic Repository With EF 4.1 what is the point.

This has all left me a bit confused...is the only real way to test a method like this to create a Repository Layer? Is it even worth unit testing this method?

Community
  • 1
  • 1
woggles
  • 7,444
  • 12
  • 70
  • 130

1 Answers1

2

Wrap the ObjectContext class in a wrapperclass -- let's call it ContextWrapper for fun -- that only exposes what you need from it. Then you can inject an interface of this (IContextWrapper) in to your class with your method. A wrapper can be mocked with no hooks attached to the outside world. The treestructure, as you say, is easy to create, and get from your mock object. Thus making your test TRUE unittests instead of a kind of integration test.

Morten
  • 3,778
  • 2
  • 25
  • 45