Here are some annotation and their usages that I have come across when I am testing using JUnit
@BeforeClass – Run once before any of the test methods in the class, public static void
@AfterClass – Run once after all the tests in the class have been run, public static void
@Before – Run before @Test, public void
@After – Run after @Test, public void
@Test – This is the test method to run, public void
@RunWith – You can also assign a @RunWith annotation to indicate what class JUnit to be handled with. Below is example usage of Parameterized.class.
@Suite – This annotation is used to bundle test cases and run them together. You would use both @RunWith and @Suite annotations. Let’s say you already have TestSomething1 & TestSomething2 that runs the tests fine. Now in order to run them together, you can create a class called something like TestSuite and put them all in there like example below.
@Ignore – mainly used for temporarily disabling a test or a group of tests. Simply adding this above a function will ignore this unit test to be included:
If you require to ignore the entire class, you can
Mockito - You will require to include dependancy library and add into your classpath called mokito-all. The test do not necessarily require any special annotation but I thought it worthwhile to mention here. Basic idea of Mocking an object is to create an accessible object for unit test to work. For more information: [Mockito](https://www.tutorialspoint.com/mockito/)
@Rule – Rules allow very flexible addition or redefinition of the behavior of each test method.
NOTE: I have never used below annotations in the practice, however, they seem interesting after reading about them.
@Category, @IncludeCategory, @ExcludeCategory: You can group tests into Categories.
@DataPoint, @DataPoints, @FromDataPoints, @ParametersSuppliedBy: Annotating an field or method with @DataPoint will cause the field value or the value returned by the method to be used as a potential parameter for theories in that class. Annotating a parameter of a @Theory method with @FromDataPoints will limit the datapoints considered as potential values for that parameter to just the @DataPoints with the given name. Annotating a @Theory method parameter with @ParametersSuppliedBy causes it to be supplied with values from the named ParameterSupplier when run as a theory.
@TestedOn: The @TestedOn annotation takes an array of values to be used as data points for the annotated parameter.
Share this post
I am a passionate software developer working in Downtown, Vancouver. I strongly believe in art of algorithms and together with it to write clean and efficient software to build awesome products. If you would like to connect with me, choose one from below options :) You can also send me an email at