创建断言

发布于 2025-01-16 06:55:38 字数 455 浏览 5 评论 0原文

所以我想创建一个断言类,就像 AssertJ 的工作方式一样。我在开始时遇到困难。


    public class Assertion {
    
        static object assertThis(Object o){}
        static Integer assertThis(int i){}
        static String assertThis(String s){}
        static Object isNotNull(){}
    
    }

我的问题是 JUNIT 如何接受特定的对象/字符串/int 并存储它?假设我传入一个 Assertion.assertThis("hello").isNotNull() 我应该返回一个字符串对象。我需要一个字段来存储目标文件吗?通过assertThis 方法传递的不同对象会如何改变这一点?

So I want to create an assertion class like how AssertJ works. I'm having trouble getting started.


    public class Assertion {
    
        static object assertThis(Object o){}
        static Integer assertThis(int i){}
        static String assertThis(String s){}
        static Object isNotNull(){}
    
    }

My question is how does JUNIT take in a particular object/string/int and store it? Let's say I pass in a Assertion.assertThis("hello").isNotNull() I should be getting a string object back. Do I need a field to store the object file? And how is that changed by the different objects being passed through the assertThis method?

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

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

发布评论

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

评论(1

无所谓啦 2025-01-23 06:55:38

我不认为这就是 JUnit 的工作原理(但是 AssertJ 会)。

但是,是的,您使用静态方法创建一个实例并保存该值,然后对该值执行断言。

对静态方法(也称为工厂方法)的新调用将创建不同的实例。

这是一个非常简单的例子:


class Assert {

   // Thing we're going to evaluate
   private String subject; 

   // Factory method. Creates an instance of `Assert` holding the value.
   public static Assert assertThat(String actual) {
      Assert a = new Assert();
      a.subject = actual;
      return a;
   }

   // Instance method to check if subject is not null
   public void isNotNull() {
     assert subject != null;
   }
}

// Used somewhere else...
import static Assert.assertThat;

class Main {
  public static void main( String ... args ) {
      assertThat("hello").isNotNull();
  }
}

I don't think that's how JUnit works (but AssertJ does).

But yes, you create an instance with a static method and hold the value, and then perform an assertion against that value.

New invocations to the static method (also know as factory method) will create different instances.

Here's a very simple example:


class Assert {

   // Thing we're going to evaluate
   private String subject; 

   // Factory method. Creates an instance of `Assert` holding the value.
   public static Assert assertThat(String actual) {
      Assert a = new Assert();
      a.subject = actual;
      return a;
   }

   // Instance method to check if subject is not null
   public void isNotNull() {
     assert subject != null;
   }
}

// Used somewhere else...
import static Assert.assertThat;

class Main {
  public static void main( String ... args ) {
      assertThat("hello").isNotNull();
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文