public class Address { public string City { get; set; } public string Country { get; set; } }
public class Contact { public string Phone { get; set; } public string Name { get; set; } public int Age { get; set; } }
public class Result { public int ID { get; set; } public int RowEffect { get; set; } }
public interface IAddressRepository { Result SaveAddress(Address address); }
public interface IContactRepository { Result SaveContact(Contact contact); }
public class Order { private IContactRepository _contactRp; private IAddressRepository _addressRp; public Order(IContactRepository contactRp, IAddressRepository addressRp) { this._contactRp = contactRp; this._addressRp = addressRp; } public int InitOrder(Address address,Contact contact) { int rowEffect=0; if (address != null && !string.IsNullOrEmpty(address.City)) { Result r = _addressRp.SaveAddress(address); rowEffect += r.RowEffect; } if (contact != null && !string.IsNullOrEmpty(contact.Name)) { Result r = _contactRp.SaveContact(contact); rowEffect += r.RowEffect; } return rowEffect; } }
[TestMethod] public void TestMockDDD() { MockFactory _factory = new MockFactory(); Mock<IAddressRepository> addressRp = _factory.CreateMock<IAddressRepository>(); Mock<IContactRepository> contactRp = _factory.CreateMock<IContactRepository>(); Order order = new Order(contactRp.MockObject, addressRp.MockObject); Address adress = new Address() { City = "温州", Country = "中国" }; Contact contact = new Contact() { Name = "张三", Age = 24, Phone = "131111111111" }; Result result = new Result(); result.ID = 10000; result.RowEffect = 1; addressRp.Expects.One .Method(d => d.SaveAddress(null)) .With(adress) .Will(Return.Value(result)); contactRp.Expects.One .Method(d => d.SaveContact(null)) .With(contact) .Will(Return.Value(result)); int count=order.InitOrder(adress, contact); Assert.AreEqual(count, 2); }
NMock学习系列(三)--- NMock在DDD领域驱动的单元测试中的应用
原文地址:http://blog.csdn.net/eye_cng/article/details/45049425