开发者

How to test a returned array contains at least one value with a certain property value

开发者 https://www.devze.com 2023-01-20 04:12 出处:网络
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\".

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");
0

精彩评论

暂无评论...
验证码 换一张
取 消