When applying TDD, do you create tests that verify expected exceptions for arguments (ArgumentException, ArgumentNullException, InvalidOperation, etc.) or just ones that are “known”, for example, CustomerDelinquentException ?
What about equals, gethashcode overrides? how would i test gethashcode?
Thanks
I always test for any exceptions I throw in my method, including
ArgumentNullException,ArgumentException, etc. I just find it’s best to test these and they’re easy to write. That way if someone ever removes those guards, the tests would break and you’d know.As far as
GetHashCode()andEquals()i test these as well if you override them. ForGetHashCode()an easy test is to create two equivalent objects (same values used in the hash code) and prove that the hash codes both objects generate are the same.You can try to test that two non-equivalent objects return different hash codes, but you’d have to make sure the values you use aren’t simply a collision. This largely depends on the algorithm you code in
GetHashCode().For Equals() test that two equivalent objects with the same fields return
trueonEquals()andfalseon two non-equivalent objects.For even more fun, I like to unit tests
DateTimedependent stuff too. This is somewhat harder, but if a method’s behavior depends onDateTimei still want to unit test them. So you can create aDateTimegenerator delegate that defaults to returningDateTime.Nowbut have it so that you can set the generator to a specificDateTime. Helps a lot with coverage in my line of work since I’m in the financial industry and a lot of logic depends on pre-market, post-market hours, etc…Then you just set up a unit test to inject a specific date time.