Returning default empty lists with Rhino Mocks

I find it good practice to always return empty lists or arrays instead of null when the method has no results, to avoid null checks in the code.

Since Rhino Mocks returns the default value for an object that is null for lists and arrays, many times I have to either add null checks back, or configure mocks to wait for the lists to return.

Is there a way to customize or extend Rhino Mocks with this behavior?

var repositoryMock = MockRepository.GenerateMock<ICustomerRepository>(); IList<Customer> customers = repositoryMock.getCustomers(); Assert.IsNotNull(customers); Assert.AreEqual(0, customers.Count ); 
+6
c # unit-testing tdd moq rhino-mocks
source share
3 answers

It turns out that this behavior 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(); } 
0
source share

There is nothing in Rhino Mocks to automatically solve your problem. The easiest solution is to simply set up an extension / utility method for each type that uses SetupResult (or repeat.any) to set the default value.

You can always be complex and list through members, check ILists / Arrays and dynamically adjust layouts - it depends on how many types you have and how many types you could devote to this utilitarian method.

Good luck

0
source share

I think changing the default behavior for mocks to return values ​​other than the defaults would be a risky step.

What happens if an error occurs in your real ICustomerRepository implementations so that it does not return an empty list and instead returns null?

If you wrote other unit tests and tested against mock versions of ICustomerRepository that automatically returned an empty list, then you would think that everything is in order. You can even create this code and think that it will work correctly, so you start your compiled application and it starts to crash.

Why? Since your classes that got into ICustomerRepository did not properly process zeros.

I would rather be explicit and set the wait in the test to return an empty IList from the getCustomers () method than something “magic” in the layout. What for? Since it improves readability, and the code works in a way that other developers who might not be so familiar with the rhino expected it to work. that is, a method without waiting returns a default value.

-one
source share

All Articles