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]开发者_如何学Go
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!
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/
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
What about:
Assert.IsTrue(cars.Any(c => c.Type == "Mustang"));
With Gallio/MbUnit you can use Assert.Exists
:
Assert.Exists(cars, x => x.Type == "Mustang");
精彩评论