To be entirely thorough in your testing of this method, I'd say you want test cases for the following three scenarios.
- the exception is thrown when the animal is alive and the number of teeth is null,
- no exception when the animal is alive and the number of teeth is not null,
- no exception when the animal is dead.
So you'll need the following.
- an
Animal
object to test, - a mocked
AnimalType
, - a valid
Tooth
object, which may or may not be a mock, - a JUnit
ExpectedException
rule - there are other ways of testing that exceptions are thrown, but this is the most versatile, so I recommend learning to use it now, and using it in all of your tests that involve exceptions, even if it seems overkill.
In your AnimalTest
class, you'll have three test methods, one for each of the scenarios that you're going to test.
numberOfTeethFailsForLiveAnimalWithInvalidTeeth
- Use the exception rule to "expect" a
ValidationException
. - Call
numberOfTeeth
on a live animal, with your mockAnimalType
. Since you haven't stubbedgetNumberOfTeeth()
, it will return null, so the exception should be thrown.
numberOfTeethSucceedsForLiveAnimalWithValidTeeth
- Stub your mock
AnimalType
to return a validTooth
fromgetNumberOfTeeth()
. - Call
numberOfTeeth
on a live animal, with your mockAnimalType
.
There is no need to verify anything - the fact that this method completes means the exception is not thrown.
numberOfTeethSucceedsForDeadAnimal
- Call whatever method you need to call, to make your animal "not alive".
- Call
numberOfTeeth
on a live animal, with your mockAnimalType
.
Again, there is no need to verify anything - the fact that this method completes means the exception is not thrown.
There are a few small things you can do to improve your code.
- Don't call your
AnimalType
parameteranimal
, when you have a type calledAnimal
- it's just too confusing. - Use a different name for the
getNumberOfTeeth()
method - it doesn't return a number, it returns aTooth
, so this name is also confusing. - Use a constant for your error message. This way, in the test method that uses the exception rule, you can verify that the text of the error is correct, but actually use the constant when you do this. Not duplicating the text reduces the danger of changing the message in the application class but not in the test class.