简体   繁体   中英

Redundant assert statements in .NET unit test framework

Isn't it true that every assert statement can be translated to an Assert.IsTrue, since by definition, you are asserting whether something is true or false?

Why is it that test frameworks introduce options like AreEquals, IsNotNull, and especially IsFalse? I feel I spend too much time thinking about which Assert to use when I write unit tests.

You can use Assert.IsTrue all the time if you prefer. The difference is Assert.AreEqual and the like will give you a better error message when the assertion fails.

NUnit (and probably other frameworks) now supports syntax like this:

Assert.That(foo, Is.Equal.To(bar))

Given enough extra code on your part, yes it's true that almost every Assent.XXX can be turned into an Assert.IsTrue call. However there are some which are very difficult to translate like Throws

Assert.Throws<ArgumentNullException>(() => x.TestMethod(null));

Translating that to an Assert.IsTrue is possible but really not worth the effort. Much better to use the Throws method.

Yes,

The AreEqual(obj1, obj2) basically does a Assert.IsTrue(obj1.Equals(obj2)). So, I would say this is true.

But perhaps they introduce those overloads for readability, per example make it obvious they want to compare two objects, or check if a value is equal to false.

It is very simple - to make your test code more readable .

Which is more readable

Assert.IsTrue(quantity > 0)

or

Assert.That(quantity, Is.GreaterThan( 0 ))

Don't you think the second option is more readable?

You can write framework agnostic asserts using a library called Should. It also has a very nice fluent syntax which can be used if you like fluent interfaces. I had a blog post related to the same.

http://nileshgule.blogspot.com/2010/11/use-should-assertion-library-to-write.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM