Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing a method that returns a collection

I'm trying to write some unit tests for a service which returns collections of complex objects (IQueriable<MyObject> to give an idea) and I'm not sure how to approach the problem.

Consider this:

public IQueriable<MyObject> GetMyObjects(int someParameterA, int someParameterB) {...}

Basically, a method that, depending on the passed parameters, will output a collection of rather complex objects.

Since the application is under development, I can use a local SQL instance and I've created a method which will populate this DB with some sample data, so the service has something to work with.

I don't have much experience in writing unit tests. OK, I'll be honest, I don't have ANY experience in writing unit tests. -_- And most of the examples I saw were for methods that do some calculations and return a single result. It is thus possible to attach a data source for the test with test cases. If a method was to return the sum of two numbers, the data source would consist of three columns: the two numbers and the expected result.

So, with my limited knowledge about unit tests, I'm trying to apply the same logic to test a method that returns a collection... and I've no idea what the test should consist of (I know I could easily test the number of returned elements), let alone what the test data source with test cases should look like.

I know the VS2010 has CollectionAssert, but I guess my problem is that I don't know how to create the "expected" values in this case.

What's the best way to approach unit tests for such methods?

like image 476
Shaamaan Avatar asked Mar 11 '26 02:03

Shaamaan


1 Answers

Create a mock collection for the data source. Either full-blown objects, or if they are complex to create in tests then look at using a mocking framework perhaps, such as Moq, or Rhino Mocks.

As long as your data source contains a sufficient range of objects to cover positive, negative and exception cases then you can write a suite of tests against this data source to cover all expected outcomes from the different input states that are possible in GetMyObjects.

You want this data to be as it would be when the application is running, so even if you don't have ALL the data you would have normally, you've just got to have enough in there to cover the eventualities you want to test against, such as:

  • What happens when there's no data in the source.
    • Do we get an empty collection, or an exception?
  • What happens when there's data in the source, but doesn't match the params you pass in
  • What happens when there's data in the source, but only one of the params match
  • What happens when there's data in the source and you pass in params that should return data
  • What happens when you pass in erroneous data to the method?
  • etc....
like image 191
Mike Avatar answered Mar 12 '26 15:03

Mike