domingo, 12 de outubro de 2008

Testing your equals methods

We all know that testing is something important. But there is some situations that writing a test code could be quite confusing.
One of this situations is how to test a equals method and ensure that all the attributes are tested correctly. Most of the time we just test if all the fields are equals or not.
It is ok, but it is far from being complete and usefull.

Here is a pattern that you can follow and it will insure that all the fields are being tested correctly:

  1. Create two values for each of your class attribute, with different values between them;
  2. Create two objects, instances of the class that you want to test, call one as base and the other as ref;
  3. Make this block of code for each attribute (it doesn't matter the sequence):
    base.setAttribute(ATTRIBUTE);
    ref.setAttribute(DIF_ATTRIBUTE);
    assert !base.equals(ref);
    ref.setAttribute(ATTRIBUTE);
    assert base.equals(ref);

Making things like this will insure that your test code for equals works perfect. Let's say that it is a little bit painful to make it for a big class, but of course you could automate it.

2 comentários:

Codename X disse...

painful, my friend, painful... lol

Speaking seriously, it is common for us to misspell words on a language that, well, we don´t speak everyday, so I recommend the spelling check tool from Firefox. ;)

Cheers!

Link d'Alekine disse...

Sorry my friend, I just corrected my terrible mistake ;)