Home > Software design >  Creating assertions
Creating assertions

Time:03-23

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?

CodePudding user response:

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