Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it considered good practice to test presence of annotations using reflection in a unit test?

(this post explains WHY I would want to do this: Good patterns for unit testing form beans that have annotation-based validation in Spring MVC)

Is it considered good practice to write a unit test to just test configuration/annotations on a field or a class? For example if you have:

@AnnotatedClass
public class MyClass {

@AnnotatedField1
@AnnotatedField2
private string myField;

}

Is there any point in writing a unit test that checks the presence of annotations above?

like image 963
Ashkan Aryan Avatar asked Mar 02 '12 10:03

Ashkan Aryan


People also ask

Which annotation is used for unit testing?

A JUnit test is a method contained in a class which is only used for testing. This is called a Test class. To define that a certain method is a test method, annotate it with the @Test annotation. This method executes the code under test.

What is the purpose of the annotation @test?

In any automation script, @Test annotation is the important part, where we write code/business logic. If something needs to be automated, that particular code needs to be inserted into the test method. The test method then executes @Test by passing attributes.

Which annotations can be used to run quick unit tests?

The @SpringBootTest annotation can be used to run quick unit tests in Spring Boot.


2 Answers

The basic answer is "Yes - it's fine to check for annotations in unit tests"

Always ask yourself "what am I testing". Unit tests test that the "code is correct" at a class/method level.

You are not really "testing" the code, but you are asserting that coders have correctly annotated certain fields, which in your case is part of asserting that "code is correct", so "yes" - I think it's acceptable to "test" this.

Another option is to make this assertion part of the code style checking phase of your build (if you're doing that) - you would have to write a custom code style to do it, but I feel that would be a more appropriate place to check this. However, that's probably a bit painful to set up, so just do it as a unit test.

like image 93
Bohemian Avatar answered Oct 02 '22 23:10

Bohemian


I would't say so but it's only my personal opinion. Presence of particular annotations and their correct usage can be tested within integration tests easily. Personally, I follow rule that within unit tests I cover only java code of a particular class. DB mappings, JSR annotations, GWT UiFields markers and so on are tested within integration tests.

like image 41
omnomnom Avatar answered Oct 02 '22 23:10

omnomnom