This is the 26th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Assertion mechanism

When we write code, we always make assumptions, and assertions are used to capture those assumptions in our code. You can think of assertions as an advanced form of exception handling. Assertions are represented as Boolean expressions that the programmer believes are true at a particular point in the program. Assertion validation can be enabled and disabled at any time, so assertions can be enabled at test time and disabled at deployment time. Using assertions can create more stable, better quality, and easy to debug code.

These Assertions method is org. Junit. Jupiter. API. The Assertions of static methods.

Now, let’s demonstrate our assertion mechanism

Let’s write a simple logical code, let’s add two numbers, and then let’s judge by the number returned and our ideal number

@displayname (" testSimpleAssertions ") void testSimpleAssertions(){int addition = 2; assertEquals(5,addition); } int addition(int i,int j){ return i+j; }Copy the code

This is where we assert that the mechanism works correctly

Notice, we changed a number, so we can see how our correct result is different from our test result, and we can also customize our error message, okay

This function is used to determine whether our returns are equal, and the assertSame method is used to determine whether our objects are the same

If the previous assertion fails, none of the subsequent programs will execute

Combined assertions

That is, we decide that our assertions are successful only if all of them succeed, and as long as one of them fails, all of them fail, using assertAll

AssertAll (" Test ", ()->assertTrue(true), ()->assertEquals(1,1)); }Copy the code

Our combined assertions write error messages in a single assertion

Abnormal assertion

This is probably a little bit weird, we need errors to work, we can’t work without errors, we write a mathematical error, we use exception assertions,

@ Test @ DisplayName (" exceptional assertions) "void testException () {assertThrows (ArithmeticException. Class, () - > {int I = 0/0. },"10/0 normal?" ); }Copy the code

But he didn’t report an error, he did report an error when the calculation was correct

Fail fast

If you suddenly don’t want to test how to do, that will happen ah, use fast failure, directly lead to test failure, in fact, it is not the use of this, once we have this result, test down also has no sense, we can use fast failure, right

@displayName (" fast fail ") void testFail(){if(2==2){fail(" test failed "); }}Copy the code