如何在 Moq 中注入依赖项以进行单元测试
How do I inject dependencies in a Moq for a Unit Test
我有一个 DbContext,我正在使用 Moq 进行单元测试。 DbContext 有两个依赖项,我在主程序中用 Autofac 注入了这两个依赖项。当我进行单元测试时,Moq 告诉我它找不到无参数构造函数。我在我的 DbContext 中添加了一个无参数构造函数,并且单元测试通过了。有没有办法像我在主程序中那样用 Autofac 注入 DbContext 依赖项?
这是我的单元测试:
[TestMethod]
public void GetAllPersons_orders_by_name()
{
var data = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe"},
new Person { FirstName = "Bill" , LastName = "Smith"},
new Person { FirstName = "Fred" , LastName = "Williams"}
}.AsQueryable();
var mockSet = new Mock<DbSet<Person>>();
mockSet.As<IQueryable<Person>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<Person>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<Person>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<Person>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var mockContext = new Mock<MyContext>();
mockContext.Setup(c => c.People).Returns(mockSet.Object);
var service = new PeopleService(mockContext.Object);
var people = service.GetAllPeople();
Assert.AreEqual(3, people.Count);
Assert.AreEqual("John", people[0].FirstName);
Assert.AreEqual("Bill", people[1].FirstName);
Assert.AreEqual("Fred", people[2].FirstName);
}
您可以在创建模拟对象时添加构造函数参数。所以在这种情况下它会是这样的:
var mockContext = new Mock<MyContext>(myDependecy1, myDependency2 ...);
我有一个 DbContext,我正在使用 Moq 进行单元测试。 DbContext 有两个依赖项,我在主程序中用 Autofac 注入了这两个依赖项。当我进行单元测试时,Moq 告诉我它找不到无参数构造函数。我在我的 DbContext 中添加了一个无参数构造函数,并且单元测试通过了。有没有办法像我在主程序中那样用 Autofac 注入 DbContext 依赖项?
这是我的单元测试:
[TestMethod]
public void GetAllPersons_orders_by_name()
{
var data = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe"},
new Person { FirstName = "Bill" , LastName = "Smith"},
new Person { FirstName = "Fred" , LastName = "Williams"}
}.AsQueryable();
var mockSet = new Mock<DbSet<Person>>();
mockSet.As<IQueryable<Person>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<Person>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<Person>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<Person>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var mockContext = new Mock<MyContext>();
mockContext.Setup(c => c.People).Returns(mockSet.Object);
var service = new PeopleService(mockContext.Object);
var people = service.GetAllPeople();
Assert.AreEqual(3, people.Count);
Assert.AreEqual("John", people[0].FirstName);
Assert.AreEqual("Bill", people[1].FirstName);
Assert.AreEqual("Fred", people[2].FirstName);
}
您可以在创建模拟对象时添加构造函数参数。所以在这种情况下它会是这样的:
var mockContext = new Mock<MyContext>(myDependecy1, myDependency2 ...);