Home Ask Login Register

Developers Planet

Your answer is one click away!

Daniel Devo February 2016

Testing framework with many Asserts per line

is there a c# testing-framework that allows to have multiple assertions concentenated together in one statement, like this:

Assert.AreEqual("valueA", object.A).AreEqual( "valueB", object.B)...

instead of

Assert.AreEqual("valueA", object.A);
Assert.AreEqual( "valueB", object.B);

That would make testing-code much shorter, right?

Thank you!


gillyb February 2016

I don't think you'll find a framework like this, since most resources will tell you that it's a good practice to keep a single assert in each test you write.

Having multiple asserts chained together will make it much harder to understand which of those failed, when they fail (and they will definitely fail at some point), and when debugging.

If you're still determined to do that, then wrapping the testing framework you're using to make them chainable should be pretty easy, and would probably look something like this:

public class Assertion {
    public Assertion AssertEquals(object actual, object expected) {
        // TODO: call your framework Assert.AreEqual() here
        Assert.AreEqual(a, b);
        return this;

// and now you can do something like this :
new Assertion()
    .AssertEquals("objectA", object.A)
    .AssertEquals("objectB", object.B);

(This isn't a working example, but just an idea on how to go about implementing this).

Either way, 'shorter code' should never be your final target. The target should be having readable code. Type less by using your IDE's autocomplete features (i.e.: Visual Studio's Intellisense).

...and if you're still very determined to have the shortest code possible (which I strongly don't recommend) then just do something like this:

public static void a(object a, object b) {
    Assert.AreEqual(a, b);

and then your test will look like this :

a("objectA", object.A);
a("objectB", object.B);

like I said, this isn't readable... :/

NikolaiDante February 2016

FluentAssertions lets you do things like this:

string actual = "ABCDEFGHI";

(More examples on the documentation)

That said, multiple asserts are troublesome at best, and chaining them together would make it even harder to see which assert failed. See Assertion Roulette on XUnit patterns.

Post Status

Asked in February 2016
Viewed 3,421 times
Voted 8
Answered 2 times


Leave an answer

Quote of the day: live life