Andy
Andy

Reputation: 11462

Unit testing for either/or conditions

The module I'm working on holds a list of items and has a method to locate and return an item from that list based on certain criteria. the specification states that "...if several matching values are found, any one may be returned"

I'm trying to write some tests with Nunit, and I can't find anything that allows me to express this condition very well (i.e. the returned object must be either A or B but I don't mind which)

Of course I could quite easily write code that sets a boolean to whether the result is as expected and then just do a simple assert on that boolean, but this whole question is making me wonder whether this is a "red flag" for unit testing and whether there's a better solution.

How do experienced unit testers generally handle the case where there are a range of acceptable outputs and you don't want to tie the test down to one specific implementation?

Upvotes: 1

Views: 1933

Answers (2)

Charlie
Charlie

Reputation: 13726

Since your question is in rather general form, I can only give a rather general answer, but for example...

Assert.That(someObject, Is.TypeOf<A>().Or.TypeOf<B>());
Assert.That(someObject, Is.EqualTo(objectA).Or.EqualTo(objectB));
Assert.That(listOfValidOjects, Contains.Item(someObject));

It depends on the details of what you are testing.

Upvotes: 4

GhostCat
GhostCat

Reputation: 140427

I am coming from Java, JUnit and parametrized tests, but it seems that nunit supports those as well (see here).

One could use that to generate values for your different variables (and the "generator" could keep track of the expected overall result, too).

Using that approach you might find ways to avoid "hard-coding" all the potential input value combinations (as said: by really generating them); but at least you should be able to write code where that information of different input values together with the expected result is more nicely "colocated" in your source code.

Upvotes: 0

Related Questions