1

While writing Integration tests for spring applications, I tend to come across checks for different Multilevel Data Objects For Eg: enter image description here

AssertNotNull("Node 10 is null", getNode1().getNode8().getNode10().getNode7());

This assertions works well provided that Objects A -> B -> C are not null, otherwise if any one of these is null, you end up with an NPE.

On a first view a plausible solution seems to all parent nodes sequentially

AssertNotNull("Node 1 is null", getNode1());
AssertNotNull("Node 8 is null", getNode1().getNode8());
AssertNotNull("Node 10 is null", getNode1().getNode8().getNode10());
AssertNotNull("Node 7 is null", getNode1().getNode8().getNode10().getNode7());

But if I start doing for every node I would end up having a bunch of cluttered up repeated code floating around.

As it is not development code and I would like to see the cause of the failure and not a raw NPE, specially when I have 100 such tests that assert these. What would be the best practice in this case to avoid NPE or not avoid it at all?

1

In your structure Node10 might be NULL in two cases

  1. Either you can successfully pass the tree up to Node8 and then you realize that the reference to Node10 does not exist
  2. Or you realize that some node on the route to Node10 does not exist, hence reference to Node10 does not exist also (it does not even refer to null, it just does not exist, so Node10 cannot be asserted to be not-null)

So to make your assertion you just need some algorithm that would know the way to Node10 (what the algorithm would be depends on how your structure is built, for example it might be a recursion) and pass node-by-node checking if the next-step exists on each level.

  • What does this have to do with Algorithms? – Anirudh Jun 5 '18 at 18:21
  • Obviously to avoid code repeating you need to bypass your data structure and apply the same assertion pattern on each level. How you implement bypassing (whatever the structure is) depends on how that structure is built. – Alexey R. Jun 5 '18 at 18:26
  • So you agree that NPE should be avoided in integration tests? I think with that Algorithm you might be referring to Elvis pattern from scala or groovy – Anirudh Jun 5 '18 at 18:51
  • 1
    Yes, NPE should be avoided unless we test some action throws it explicitly. – Alexey R. Jun 5 '18 at 20:11

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.