1

I have a class with 4 parametres. Also have a test that puts null object. Is it possible to catch specificaly this null? I mean some tests put IlligalArgumentException.class inside tests . So if I try to catch this null object with try catch block for whole costructor block this one works but other tests crushes and vice versa.

class Quadrilateral extends Figure{
        Quadrilateral(Point a, Point b, Point c, Point d){
    }
}
    @Test
        void testConstructor() {
            Figure q = null;
            q = q(0, 0, 0, 1, 1, 1, 1, 0);
            q = q(-2, 2, -3, 1, 0, 1, 0, 2);
        }
    
    @Test
        void testConstructorNullACase() {
            assertThrows(IllegalArgumentException.class, () -> q(null, new Point(-3, 1), new Point(0, 1), new Point(1, 9)));
        }
1
  • You could use @NotNull. This does not throw an IllegalArgumentException but is marks null arguments in the IDE highlighting: stackoverflow.com/q/34094039 Commented Jul 3, 2022 at 21:05

1 Answer 1

0

You can use the Lombok API for this. If you annotate a parameter with @NonNull and it gets set to null it throws an NullPointerException.

Lombok code:

public NonNullExample(@NonNull Person person) {
    super("Hello");
    this.name = person.getName();
  }

Vanilla Java:

public NonNullExample(Person person) {
    super("Hello");
    if (person == null) {
      throw new NullPointerException("person is marked non-null but is null");
    }
    this.name = person.getName();
  }

More infos at: Lombok

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.