1

I'm using EF6. The generated code is something like:

public partial class MyDataContext : DbContext
{
    public MyDataContext() : base("name=mydata")
    {
    }

    public virtual DbSet<Book> Books { get; set; }
}

Then I have a generic repository like:

public class GenericRepository<TObject> where TObject : class
{
    protected readonly MyDataContext Context;

    protected GenericRepository(MyDataContext context)
    {
        Context = context;
    }

    public virtual TObject Update(TObject data, int id)
    {
        if (data == null)
            return null;

        TObject obj = Context.Set<TObject>().Find(id);
        if (obj != null)
        {
            Context.Entry(obj).CurrentValues.SetValues(data);
            Context.SaveChanges();
        }

        return obj;
    }
}

Then I have a service that uses the GenericRepository to update data:

public class MyDataService<TObject> where TObject : class
{
    private readonly MyDataContext context;

    public MyDataService(MyDataContext ct)
    {
        context = ct;
    }

    public TObject Update(TObject obj, int id)
    {
        var r = new GenericRepository<TObject>(context);
        return r.Update(obj, id);
    }
}

So I can update a books with something like this:

var ds = new MyDataService<Book>(new MyDataContext());
var data = ds.Update(new Book { Name = "New Name" }, 1);

This is working fine. Next I try to use Moq to unit test the above code with something like:

var updatedBook = new Book { Name = "Update Book Name" };

var mockSet = new Mock<DbSet<Book>>();
var mockContext = new Mock<MyDataContext>();
mockContext.Setup(c => c.Books).Returns(mockSet.Object);
mockContext.Setup(c => c.Set<Book>().Find(It.IsAny<object[]>()))
            .Returns<object[]>(ids => chips.FirstOrDefault(d => d.Id == (int)ids[0]));

var service = new MyDataService<Book>(mockContext.Object);
var data = service.Update(updatedBook, 1);

However, I get an exception on the Context.Entry(obj).CurrentValues.SetValues(data) line.

How do I mock the Update method properly?

1
  • 2
    abstract all the things. :), but seriously, your classes should depend on abstractions and not on concretions. that said. All the above classes should be abstracted behind interfaces. And you are also coupling different layers to closely. service layer doesn't need to know about data context
    – Nkosi
    Commented Dec 5, 2016 at 21:25

3 Answers 3

4

You could implement an interface for MyDataService to be able to mock it

public Interface IMyDataService<TObject> where TObject : class
{
   TObject Update(TObject obj, int id);
}

public class MyDataService<TObject>:IMyDataService<TObject>
 where TObject : class
{
    private readonly MyDataContext context;

    public MyDataService(MyDataContext ct)
    {
        context = ct;
    }

    public TObject Update(TObject obj, int id)
    {
        var r = new GenericRepository<TObject>(context);
        return r.Update(obj, id);
    }
}

Moq:

var mockDataService = new  Mock<IMyDataService<Book>>();
mockDataService.Setup(c=> c.Update(It.Any<Book>(),It.Any<int>()).Returns(updatedbook);
3
  • Could you show how my test method should look like by using this interface?
    – notlkk
    Commented Dec 5, 2016 at 21:25
  • Thanks for the updated example. Do I call mockDataService.Update in the test method to invoke because I can't seem to do that.
    – notlkk
    Commented Dec 5, 2016 at 21:39
  • @notlkk just call mockDataService.Object.Update Commented Dec 5, 2016 at 21:51
3

The service should be dependent on the repository. Passing the context directly to the service is misleading as what the service really needs and uses is the repository.

Your classes should depend on abstractions and not on concretions. That said, all the above classes could be abstracted behind interfaces. but for now I'll focus on the service class and it's dependence on the repository. You are coupling different layers too closely. Service layer doesn't need to know about data context

Abstract the repository to allow for easier testability

interface IGenericRepository<TObject> where TObject : class {
    TObject Update(TObject data, int id);
}

public class GenericRepository<TObject> : IGenericRepository<TObject> where TObject : class {
    protected readonly MyDataContext Context;

    public GenericRepository(MyDataContext context) {
        Context = context;
    }

    public virtual TObject Update(TObject data, int id) {
        if (data == null)
            return null;

        TObject obj = Context.Set<TObject>().Find(id);
        if (obj != null) {
            Context.Entry(obj).CurrentValues.SetValues(data);
            Context.SaveChanges();
        }

        return obj;
    }
}

The service would only now need to know about the repository abstraction, not its implementation details.

public class MyDataService<TObject> where TObject : class {
    private readonly IGenericRepository<TObject> repository;

    public MyDataService(IGenericRepository<TObject> repository) {
        this.repository = repository;
    }

    public TObject Update(TObject obj, int id) {
        return repository.Update(obj, id);
    }
}

So now the service can be tested in isolation without any need to worry about any data context

//Arrange
var updatedBook = new Book { Name = "Update Book Name" };
var id = 1;

var mockRepository = new Mock<IGenericRepository<Book>>();
mockRepository
    .Setup(m => m.Update(updatedBook, id))
    .Returns(updatedBook);

var service = new MyDataService<Book>(mockRepository.Object);
//Act
var data = service.Update(updatedBook, id);

//Assert
//...

When it's time to unit test the repository implementation in isolation, then you can follow the same structure and abstract the context for the repository implementation.

5
  • Since I already have other mock tests working (like Add, Get...) I'm not sure how to make your design/implementation work with those. With Add and Get I do want to test the code in repository instead of just doing a .Returns to return a mock object. Could you also show an example of doing that?
    – notlkk
    Commented Dec 5, 2016 at 22:57
  • I'm upvoting this and making it the right answer since I believe it's the right design and implementation. I also figured it out how to replace my current moq test on Add and Update operation. Thanks.
    – notlkk
    Commented Dec 6, 2016 at 7:05
  • I see what you did here. You've abstracted your repository code, hence you don't need to test the DbContext.Update here. However, you can't continue to abstract this, eventually, you will have code with the DbContext.Update that has to be tested and unfortunately, this didn't answer that question.
    – Rhyous
    Commented Jun 24, 2021 at 20:37
  • @Rhyous this answer relates specifically isolated unit testing. If you have to test an actual Update then you are straying into integration testing and an in-memory context can be used for that
    – Nkosi
    Commented Jun 24, 2021 at 20:40
  • Oh, I know I am straying as I write my Api. Your answer, however, is the only viable solution as DbEntityEntry<TEntity> does NOT have a default constructor, so most mocking frameworks can't mock it. So there really is no choice but to abstract it to to the minimal method possible. Then to get 100% code coverage in reports you have to mark the minimal extracted code with [ExcludeFromCodeCoverage]. So, upvote.
    – Rhyous
    Commented Jun 24, 2021 at 21:06
0

I would suggest the small refactoring in order to make the testing easier and even possible. With this implementation you are relying on the implementation of the DbContext and DbEntityEntry.

At first extract interface for your context:

public inteface IMyDataContext<TObject> where TObject is class
{
    TObject FindById(int id); //call FindId
    void Update(TObject); //call DbEntityEntry SetValues
    void SaveChanges();
}

In the GenericRepository then inject the interface. This will make your life easier, you can then easily mock all method. Unit tests of the repository should verify that right methods of the context are called.

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.