我查看了其他问题,但没有什么能完全符合我的要求......主要是因为我不确定自己在寻找什么!
基本上,我现在正在处理一个新项目,我已经创建了我的DB实体的抽象层并将DAC设置为存储库。我想使用单元测试和Mock对象,但是在CRUD(特别是C)操作方面遇到了智力壁垒,我的单元测试类:
[TestClass]
public class RepositoryTest
{
private Mock<IPersonRepository> _repository;
private IList<IPerson> _personStore;
[TestInitialize()]
public void Initialize()
{
_personStore= new List<IPerson>() {
new Person() { Name = "Paul" },
new Person() { Name = "John" },
new Person() { Name = "Bob" },
new Person() { Name = "Bill" },
};
_repository = new Mock<IPersonRepository>();
_repository.Setup(r => r.Entirely()).Returns(_personStore.AsQueryable());
}
[TestCleanup()]
public void Cleanup()
{
_personStore.Clear();
}
[TestMethod()]
public void Can_Query_Repository()
{
IEnumerable<IPerson> people = _repository.Object.Entirely();
Assert.IsTrue(people.Count() == 4);
Assert.IsTrue(people.ElementAt(0).Name == "Paul");
Assert.IsTrue(people.ElementAt(1).Name == "John");
Assert.IsTrue(people.ElementAt(2).Name == "Bob");
Assert.IsTrue(people.ElementAt(3).Name == "Bill");
}
[TestMethod()]
public void Can_Add_Person()
{
IPerson newPerson = new Person() { Name = "Steve" };
_repository.Setup(r => r.Create(newPerson));
// all this Create method does in the repository is InsertOnSubmit(IPerson)
// then SubmitChanges on the data context
_repository.Object.Create(newPerson);
IEnumerable<IPerson> people = _repository.Object.Entirely();
Assert.IsTrue(people.Count() == 5);
}
}
我的 Can_Query_Repository 方法成功了,但是 Can_Add_Person 方法无法通过断言。现在我需要做什么:
- 设置 Mock 存储库的 .Create 方法以将元素添加到 _personStore 中吗?
- 还需要类似的其他操作吗?
- 放弃所有希望,因为我想要实现的不可能,并且我做错了一切!
像往常一样,任何帮助/建议都将不胜感激!