To test a method that returns a clone of the object it is called on, i need to re-run the test suite on the newly created object if i am to ensure that full functionality is retained, i found my instinct was to clone the object then call all other test methods in sequence i order to reduce code duplication. However that approach now smells to me and i can't pinpoint why. Is there a better way to test this kind of functionality?

  • In general, I don't try to be DRY in unit tests. I do try to be clear, however. I believe each test should stand on its own; there shouldn't be any external dependencies, other than the code under test and perhaps a mocking framework. Jul 9, 2013 at 18:51

1 Answer 1


Such testing might be cleaner with code contracts. The test methods you are talking about should be invariants (must hold true before and after all public method calls) on your object, rather than unit tests. Your clone function would have preconditions and postconditions (the postcondition would require that the object be equal to the object it cloned, and possibly that its reference was not equal).

In some cases, your code could be statically tested for compliance with such invariants.

  • I agree, this sounds like a requirement that should be enforced by the Clone operation
    – neontapir
    Jul 10, 2013 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.