开发者

EF4.1 Code First Mocking With Moq

I am trying my hand on EF with EF4.1 Code Frist. I have developed my models, like:

public class User
{
    [Key]
    public int Id{get;set;}
    [Column("first_name")]
    [StringLength(30)]
    public string FristName{get;set;}
    //............
    //..............
}

I have written an interface also:

public interface IUser
{
    IDbSet<User> Users{get;}
}

My context class looks like this:

public class UserContext : DbContext开发者_高级运维, IUser
{
    public DbSet<User> Users{get;set;}

    IDbSet<User> IUser.Users{get return{Users;}}
}  

Now I am at loss how to use Moq to mock this repository and do unit testing. Maybe I am new to unit testing with mocking.

Kindly advise me or point me to some resources where I can learn how to use Moq with EF4.1.


A great pattern to use when mocking data access is the Repository pattern and Unit of work. When you have abstracted data access to a Repository interface you can use a mocking framework like moq. To provide you with a testable repository.

var mockUnitOfWork = new Mock<IUnitOfWork>();
mockUnitOfWork.SetupGet(p => p.UserRepository.GetSomeUsers)
.Returns(new List<User> { "Username", "email","etc"}));  

You can then use the mockUnitOfWork and repository to test data access without having to hit the database as its only accessing an in memory list of users.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜