如何捕获特定的空对象?

发布于 2025-02-13 04:25:22 字数 652 浏览 1 评论 0原文

我有一个带4个参数的课程。也有一个测试,可将空对象放置。 是否可以捕获该零的特异性? 我的意思是有些测试将IlligalargumentException.class插入测试。因此,如果我尝试用尝试捕获块的整个Coctuctor Block捕获这个空对象,则此功能可行,但其他测试也会陷入困境,反之亦然。

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)));
        }

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)));
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

彼岸花ソ最美的依靠 2025-02-20 04:25:22

您可以使用Lombok API。如果您用@nonnull注释一个参数,并且将其设置为null它将抛出nullpointerexception

LOMBOK代码:

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();
  }

更多信息: lombok

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文