views:

51

answers:

3

I'm trying to test that a certain function I'm building will add objects to a collection when supplied with a collection of Ids.

My test looks something like this:

var someClass = new SomeClass();
var someIds = new List<Guid> { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };

someClass.AddIds(someIds);

Asset.That(someClass.IdsInClass, List.???);

The property IdsInClass is actually an IList and for the sake of argument lets say that it looks something like this:

public class SomeOtherClass
{
    public Guid Id { get; set; }
    public SomeClass Parent { get; set; }
    //other properties we don't care about for this test
}

I want to make sure that all the ids I made in my test are being added to someClass.IdsInClass

What is the best way to do that?

I was thinking maybe an expression would work like so:

Assert.That(someClass.IdsInClass, 
    List<SomeOtherClass>.HasAll(x => someIds.Contains(x.Id));

But I don't know if anything like that exists.

A: 

You could use LINQ expressions that resolve to a boolean. For example, I write code similar to the following with NUnit tests:

List<string> items = ...
Assert.That(items.All(item => item.Contains("x")))

Does that help?

jrummell
Kind of. What I want to do, though, is verify that ALL the Guids I have in my list show up in the other collection. Just having one isn't good enough.
Joseph
As BioBuckyBall suggested, you can use the All Linq extension method instead of Any.
jrummell
+3  A: 

I would use Linq's All...

Assert.True( someIds.All( id => someClass.IdsInClass.Contains( id ) ) );
BioBuckyBall
Oh now that looks interesting. I've never seen that before. I'll see if I can use that for my unit test, thanks!
Joseph
@Joseph No problem.
BioBuckyBall
+1  A: 

There is a dedicated assertion in Gallio/MbUnit for that specific test case:

Assert.ForAll(someIds, id => someClass.IdsInClass.Contains(id));

The benefit is that Gallio tells which particular elements of sequence are failing (if any). That's certainly better than just getting a generic message indicating that the expression evaluated by Assert.IsTrue is just not true.

Yann Trevin