Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning empty lists as default with Rhino Mocks

I think it's a good practise to always return empty lists or arrays instead of null when a method comes up with no results to avoid null checks in the code.

Because Rhino Mocks returns the default value for an object, which is null for lists and arrays, a lot of times I have to either add the null checks back in or setup the mocks with expectations to return lists.

Is there a way to configure or extend Rhino Mocks with this behaviour?

var repositoryMock = MockRepository.GenerateMock<ICustomerRepository>();
IList<Customer> customers = repositoryMock.getCustomers();

Assert.IsNotNull(customers);
Assert.AreEqual(0, customers.Count );
like image 575
Dala Avatar asked Feb 12 '09 07:02

Dala


1 Answers

Turns out that this behaviour is possible with Moq as long as the returned object is IEnumerable. The following tests pass:

[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();
}
like image 93
Dala Avatar answered Oct 17 '22 17:10

Dala