Reputation: 227
I have an interface that defines a method which is meant to throw a specific exception when a condition is not met.
interface PrizePotInterface
{
/**
* @throws PrizePotEmptyException
*/
public function claimPrize(EntryInterface $entry);
}
I have two classes which implement this interface, both of which have similar logic to determine whether to throw the exception.
class SequentialPrizePot implements PrizePotInterface
{
public function claimPrize(EntryInterface $entry)
{
if ($this->isEmpty()) {
throw new PrizePotEmptyException();
}
// prize claim logic
}
}
class RandomPrizePot implements PrizePotInterface
{
public function claimPrize(EntryInterface $entry)
{
if ($this->isEmpty()) {
throw new PrizePotEmptyException();
}
// prize claim logic
}
}
I need to write a unit test that checks that an empty prize pot throws PrizePotEmptyException
, and I need this test to apply to both implementations.
I can see three options:
Write the same test method in each test class to check for the exception. Simple and easy, but not very DRY.
Make both test classes inherit a common (abstract) PrizePotTest
class which checks for the exception. (Do test*
methods in parent
classes even get run by PHPUnit?)
Write the test in a trait and use it in each test class. (Again, PHPUnit may not allow this kind of test.)
I’m unsure which of these (if any) is considered good unit testing practice.
Upvotes: 0
Views: 482
Reputation: 35139
Don't worry for now that it's for a test - how would you write the code to do what you needed, if it was regular code? Also, it may be clearer initially to just copy & paste any code you do write, and then if you need a third instance, refactor it out to a common call - just like 'normal' code.
I do however tend towards simple, obvious code, even when it may have duplication as well, despite the fact it could be more 'elegant' - and especially in tests. The best 'elegant' or DRY code, can hide some of the meaning. In business logic, that abstraction can be good, but as I said, I'd rather have explicitness in the tests.
Upvotes: 1