Issue
I am testing a method which should return an object of type Card
. Something like:
@Test
public void testPrepareCardData() {
Card card = service.prepareData(ID);
After that I want to assert that all of the attributes of card
have not been set. Let's say the method returned empty object.
One way to do it (pretty naive) is to check every attribute, like:
assertNull(card.getId());
assertNull(card.getCardNumber());
etc.
But there is many attributes and it would take some time. Is there any sophisticated solution to that ?
Solution
You can use Reflection
to perform that
Method[] methods = card.getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.getName().contains("get")) {
method.setAccessible(true);
// Act & Assert
assertNull(method.invoke(card));
}
}
More information: Reflection Oracle doc
Answered By - heaprc
Answer Checked By - Marilyn (JavaFixing Volunteer)