开发者

How to test MVC actions with Code First?

开发者 https://www.devze.com 2023-03-16 13:03 出处:网络
I\'m trying to test MVC actions, so i created IRepository and MockRepository public class Repository : DbContext, IRepository

I'm trying to test MVC actions, so i created IRepository and MockRepository

public class Repository : DbContext, IRepository
{
    public IDbSet<TEntity> SomeEntities { get; set; }
开发者_如何学Python}

public interface IRepository : IDisposable
{
    IDbSet<TEntity> SomeEntities { get; set; }

    int SaveChanges();
}

With Create and Delete actions it was simple, but stuck with Edit action :

    private IRepository repository;

    public ActionResult Edit(TEntity entity)
    {
        if (ModelState.IsValid)
        {
            repository.Entry(entity).State = EntityState.Modified;
            repository.SaveChanges();

            return RedirectToAction("Index");
        }

        return View(entity);
    }

So i see two ways to solve this problem:

  1. should i add to IRepository new method

    DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
    

    How i could do this? DbContext.Entry method returns very specific DbEntityEntry<TEntity> type?

  2. or change the way i update entity? What is recommended way to do this?


I would normally abstract the functionality of EF more than you are, meaning my actions look the following.

private IRepository repository;
public ActionResult Edit(TEntity entity)
{
    if (ModelState.IsValid)
    {
        repository.Update(entity);
        repository.SaveChanges();

        return RedirectToAction("Index");
    }

    return View(entity);
}

then you can easily make a mock repository and test that the desired functions are called.

Note: I normally also separate my entities from my models and manage my unit of work using an action filter, but that's not really related to this post.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号