0

How to write a proper test on a method that can return a null to assign the value to a nonnull variable?

@Nonnull String abc;
if(holderForState.getNodeElementSelectedAPI() == null || holderForState.getNodeElementSelectedAPI().equals("")) {
    throw new IllegalArgumentException("SelectedAPI is empty or null during logic usage");
}
abc = holderForState.getNodeElementSelectedAPI();

Why does VS-code tell me that: Null type safety: The expression of type 'String' needs unchecked conversion to conform to '@Nonnull String'Java(16778128) on abc assignment line? I am literally testing if it is null 1 line above and throwing out of context if it is...

I tried multiple versions of this test, but I get the same. To make it simpler I am showing the assignment, whereas in reality I am using abc as a method parameter, with same outcomes.

KKorzuno
  • 3
  • 2
  • 1
    Maybe the message can't assume that `holderForState.getNodeElementSelectedAPI()` always returns the same value? Try assigning the value to a temporary variable first. – markspace Feb 28 '23 at 15:45

1 Answers1

0

You are always calling the .getNodeElementSelectedAPI(); method. It might be the case that the return type of this methods is different after the second call so it can possible get null.

I would recommend you to write your code something like

String abc = holderForState.getNodeElementSelectedAPI();
if( abc == null || abc.equals("")) {
    throw new IllegalArgumentException("SelectedAPI is empty or null during logic usage");
}

The variable abc can get null but it would still trigger the IllegalArgumentException.

Yanni2
  • 176
  • 9
  • Whats the problem with my solution? – Yanni2 Feb 28 '23 at 15:52
  • @Nonnull String abc = holderForState.getNodeElementSelectedAPI(); This line has the same warning. – KKorzuno Feb 28 '23 at 15:52
  • You removed the @Nonnull. But the whole trick is that I want abc to be Nonnull. I am supposed to use abc as a parameter in a method that has specified it as Nonnull. – KKorzuno Feb 28 '23 at 15:54
  • Ok. I cannot make it Nonnull. If I do what you both proposed, it stops the warning on the method. This Nonnull stuff is confusing as hell. – KKorzuno Feb 28 '23 at 15:57