1

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?

7
  • 1
    junit is open source. You can just look at what they do instead of asking SO to go look at it and paste the JUnit source in an answer, no? Seems a bit lazy. Commented Mar 22, 2022 at 18:02
  • 2
    As far as I know, JUnit does not have API such as assertThis(...).isNotNull(). Are you sure you're not thinking of AssertJ? If so, then take a look at §2.6.2 Custom Assertions. Commented Mar 22, 2022 at 18:08
  • see also: hamcrest Commented Mar 22, 2022 at 18:11
  • 2
    I would think that assertThis() should return an helper (or intermediate) object that has the isNotNull() method... Commented Mar 22, 2022 at 18:15
  • 1
    @GhostCat not quite. x instanceof Object will return false for x equal null. Commented Mar 22, 2022 at 19:23

1 Answer 1

2

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(); } } 
Sign up to request clarification or add additional context in comments.

3 Comments

Bear in mind that using a library like AssertJ is way better than rolling your own (they already solved a bunch of things you would find) But for learning purposes this is what you could try.
user16320675, you are correct, but then again, you shouldn't roll your own assertion framework either and if you do I think it would be expected you know how to enable assertions ( -ea flag btw)
This helped! It's for learning purposes. I tweaked it a little because i also want isNotNull to return back the same object so it can be chained again to something else.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.