Rule Annotation in JUnit

Rule Annotation in JUnit is special Annotation to set the Rule or conditions for JUnit Tests. Rules are used for special handling in JUnit. Rules are used to handle Test Cases in JUnit or Test Suites in JUnit. Rules used for additional validations common for all tests in the class set up resources before each test case execution and tear them down afterward.

 

The rule gets complete control over test case or test suite. Complete control means that the rule decides what to do before and after running Test Case and how to deal with exceptions.

Rules run separately for each test are called test rules and rules applied to the whole test case or suite is called class rules.

 

Declaring Test Rules – We declare the rule with @Rule annotation. @Rule annotation tells the JUnit that the variable which is attached to it is a rule and it must be a “public” but not static.

We can see the @Rule uses with exception class as well. Like Expected condition is a rule.

 

Expected Condition – Expected exception runs the test and catches any exception it throws. The rule is able to check whether the exception contains the right message, the right cause and whether it was thrown by the right line.

Expected exception has the private constructor and must be initialized using the static method. Each exception throwing test has to configure expected exception parameters and then call the expected method of the rule. The rule fails if:

  • the test throws any exception before the expect method call,
  • the test does not throw an exception after the expect method call,
  • thrown exception does not have the right message, class or cause.

 

The last test line throws an exception. Expected exception rule is configured right before causing the exception:

 

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply