我认为总是返回空列表或数组而不是 null 是一个好习惯 当方法没有结果时避免在代码中进行空检查。
因为 Rhino Mocks 返回一个对象的默认值,对于列表和数组来说是 null,很多时候我必须重新添加 null 检查或者设置模拟以返回列表。
有没有办法使用这种行为配置或扩展 Rhino Mocks?
var repositoryMock = MockRepository.GenerateMock<ICustomerRepository>();
IList<Customer> customers = repositoryMock.getCustomers();
Assert.IsNotNull(customers);
Assert.AreEqual(0, customers.Count );
最佳答案
结果表明 Moq 可以实现这种行为只要返回的对象是 IEnumerable。以下测试通过:
[Test]
public void EmptylListTest()
{
var repositoryMock = new Mock<ICustomerRepository>();
IEnumerable<Customer> customers = repositoryMock.Object.GetCustomers();
Assert.IsNotNull(customers);
Assert.AreEqual(0, customers.Count());
}
[Test]
public void EmptyArrayTest()
{
var repositoryMock = new Mock<ICustomerRepository>();
Customer[] customerArray = repositoryMock.Object.GetCustomerArray();
Assert.IsNotNull(customerArray);
Assert.AreEqual(0, customerArray.Length);
}
public interface ICustomerRepository
{
IEnumerable<Customer> GetCustomers();
Customer[] GetCustomerArray();
}
关于c# - 使用 Rhino Mocks 默认返回空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/540401/