views:

48

answers:

4

Hi, say I have a method I wish to test:

public Cars[] GetCars();

I want to test that the array returned by this method contains at least one car which is of type "Mustang".

How would I actually do this?

Currently I have code like:

[Test]
public void GetCars_ReturnsMustangs()
{
   Cars[] cars = GetCars();

   foreach(Car car in cars)
   {
      Assert.IsTrue(Car.Type == "Mustang");
   }
}

While this works as a test as far as I can tell I'm aware it's not a good idea to put loops inside the test?

Can anybody suggest a better alternative?

Thanks!

+3  A: 

Something like this should do the trick, just be sure to add "using System.Linq;"

[Test]
public void GetCars_ReturnsMustangs()
{
    Cars[] cars = GetCars();
    Assert.IsTrue(cars.Where(c => c.Type == "Mustang").Count() > 0);
}

(That code hasn't been tested for syntax errors but should work fine)

Edit: Replace .Count() > 0 with .Any() per @John's comment

Colin O'Dell
@colinodell .. Using Any() instead of Count would probably be better. See this reference http://blogs.teamb.com/craigstuntz/2010/04/21/38598/
John Hartsock
@John - Thanks, I didn't know about .Any() until you mentioned it. Feels like I'm learning something new about LINQ every day haha
Colin O'Dell
Thanks for the answer!
Mr Cricket
+4  A: 

Would Linq be an Option

using System.Linq

[Test]
public void GetCars_ReturnsMustangs()
{
   Cars[] cars = GetCars();
   Assert.IsTrue(cars.Any(c => c.Type == "Mustang"));
}

Edited:

Here is a great article on when to use Count() vs when to use Any()

http://blogs.teamb.com/craigstuntz/2010/04/21/38598/

John Hartsock
Thanks to this post, I just learned about `.Any()` :)
Colin O'Dell
+3  A: 

What about:

Assert.IsTrue(cars.Any(c => c.Type == "Mustang"));
Edgar Sánchez
+1  A: 

With Gallio/MbUnit you can use Assert.Exists:

Assert.Exists(cars, x => x.Type == "Mustang");
Yann Trevin