Pau*_*ann 4 .net c# moq repository linq-to-sql
我已经看过其他问题,但没有什么能与我正在寻找的东西相提并论......主要是因为我不是100%肯定我正在寻找什么!
基本上我现在正在开发一个新项目,我已经为数据库实体创建了抽象层,并将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);
}
}
Run Code Online (Sandbox Code Playgroud)
我的Can_Query_Repository方法成功,但Can_Add_Person方法无法断言.现在,我需要这样做:
一如既往,任何帮助/建议表示赞赏!
理想情况下,您会对这些进行一些集成测试,但如果您想对其进行单元测试,则可能有一些途径,包括原始问题的评论中未提及的途径.
第一个. 测试你的crud时,你可以使用.Verify检查是否真的调用了Create方法.
mock.Verify(foo => foo.Execute("ping"));
Run Code Online (Sandbox Code Playgroud)
使用Verify,您可以检查参数是否是某个类型的某个参数,以及实际调用该方法的次数.
第二个. 或者,如果要验证已在存储库集合中添加的实际对象,则可以在模拟上使用.Callback方法.
在测试中创建一个列表,该列表将接收您创建的对象.然后在您调用设置的同一行添加一个回调,它将在列表中插入创建的对象.
在断言中,您可以检查列表中的元素,包括它们的属性,以确保添加了正确的元素.
var personsThatWereCreated = new List<Person>();
_repository.Setup(r => r.Create(newPerson)).Callback((Person p) => personsThatWereCreated.Add(p));
// test code
// ...
// Asserts
Assert.AreEuqal(1, personsThatWereCreated.Count());
Assert.AreEqual("Bob", personsThatWereCreated.First().FirstName);
Run Code Online (Sandbox Code Playgroud)
在您的实际示例中,您可以创建人员,然后将其添加到设置中.在这里使用回调方法没有用.
您还可以使用此技术增加变量以计算调用它的次数.
| 归档时间: |
|
| 查看次数: |
2951 次 |
| 最近记录: |