使用模拟单元测试存储库

Unittesting Repositories using mocks

我正在尝试编写单元测试。这是我第一次使用存储库和依赖项注入来执行此操作。

我的单元测试如下所示:

[TestClass()]
public class PersonRepositoryTests
{
    Mock<PersonRepository> persoonRepository;
    IEnumerable<Person> personen;

    [TestInitialize()]
    public void Initialize()
    {
        persoonRepository = new Moq.Mock<PersonRepository >();
        personen = new List<Person>() { new Person { ID = 1, Name = "Bart Schelkens", GewerkteDagen = 200, Leeftijd = 52, Type = "1" },
                                        new Person { ID = 2, Name = "Yoram Kerckhofs", GewerkteDagen = 190, Leeftijd = 52, Type = "1" }};

        persoonRepository.Setup(x => x.GetAll()).Returns(personen);

    }

    [TestMethod()]
    public void GetAll()
    {
        var result = persoonRepository.Object.GetAll();
    }
}

我的存储库:

 public class PersonRepository
{
    DatabaseContext DbContext { get; }

    public PersonRepository(DatabaseContext dbContext)
    {
        this.DbContext = dbContext;
    }

    public virtual IEnumerable<Person> GetAll()
    {
        return DbContext.Persons.ToList();
    }

}

现在,当我 运行 我的测试时,出现以下错误:

“无法实例化 class 的代理:CoBen.Dossier.DataAccess.Repository.PersonRepository。 找不到无参数构造函数。"

所以我做错了什么,但我没有看到。 谁能帮帮我?

尝试添加无参数构造函数:)

public PersonRepository(){}

发生该错误是因为在您的单元测试中您模拟了存储库,但您的存储库 class 似乎依赖于数据上下文。

您需要在您的存储库中添加一个没有数据上下文作为依赖项的默认构造函数,如下所示:

public PersonRepository()

或模拟数据上下文。希望有帮助

您正在模拟被测系统 (sut),即 PersonRepository,您需要模拟的是它的依赖项:

[TestMethod]
public void GetAll()
{
    // *Arrange*
    var mockSet = new Mock<DbSet<Person>>(); 

    var mockContext = new Mock<DatabaseContext>(); 
    mockContext.Setup(m => m.Person).Returns(mockSet.Object); 

    // Configure the context to return something meaningful

    var sut = new PersonRepository(mockContext.Object);

    // *Act*
    var result = sut.GetAll()

    // *Assert* that the result was as expected
}

有点"air code",因为您的问题没有详细说明如何配置 DbContext 位。

MSDN 上有 worked example