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)));
        }
Cherik
  • 31
  • 1
  • 5
  • You could use `@NotNull`. This does not throw an IllegalArgumentException but is marks null arguments in the IDE highlighting: https://stackoverflow.com/q/34094039 – Japhei Jul 03 '22 at 21:05

1 Answers1

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

Japhei
  • 565
  • 3
  • 18