Learn how to use Sensei to match problematic code patterns and then amend them to agreed implementations with examples of annotation matching.
In this blog post, we will:
Sensei provides the ability to match problematic code patterns and then amend them to agreed implementations. In this example, I am using @Disabled without a parameter as the problematic code pattern.
Disabled tests without a specified reason can prove problematic over the long term because we forget why we disabled it.
The risk is that, over time, the code base moves on, the disabled test is not updated in step with the purpose of the code and eventually becomes redundant and irrelevant, and potentially never re-enabled.
During code reviews, we will often point out that it is a good idea to add an explanatory description as the annotation parameter.
We can write a recipe to detect when @Disabled is added without explanation and a Quick Fix that reminds us to add the actual reason explaining why we disabled it.
When I think about what I'm going to do, I have to:
I use Alt+Enter to Create a new Recipe.
Then add the basic descriptive text in the general information.
By making the rule a warning, any matching code is highlighted but not shown as a glaring error.
In the recipe editor, I change the Search to match an annotation.
This will highlight all annotations in the preview.
Having done that, I want to filter on the type of annotation.
I could just use Disabled but I fully qualify the class with the package so that it only matches the annotation from JUnit 5. Because the source code is shown in the preview, I can easily copy and paste this in from the actual code to avoid any typos.
I then want to match only annotations without Parameters, and I can use the GUI to do that.
For my QuickFix I will use a rewrite action.
I use the Show Variables functionality to show me the Mustache variables and preview the contents.
And then I add the extra code needed to create the place marker comment.
We have created a short video showing the recipe creation process in action.
When building a rewrite Quick Fix, it is easier when we can search for the code element that we want to rewrite, because it is then the self entity we can act on.
In this example, I used a rewrite action to amend the Annotation. Rewrite is a general-purpose action that can apply to any code element and is a good default to explore.