1

我们在代码审查中发现的一个常见问题是人们写这个:

    assertThat(thing, nullValue());

而不是这个:

    assertThat(thing, is(nullValue()));

为了更快地抓住它,我想我会尝试编写一个自定义的容易出错的检查。虽然这是一个记录不充分的领域,所以我一直在通过在 GitHub 中挖掘工作示例来做到这一点。

我到目前为止:


@AutoService(BugChecker.class)
@BugPattern(
    name = "AssertThatThingNullValue",
    summary = "`assertThat(thing, nullValue())` doesn't sound like English, wrap `nullValue` in `is`"
    severity = WARNING)
public class AssertThatThingNullValue extends BugChecker implements MethodInvocationTreeMatcher
{
    private static final Matcher<ExpressionTree> ASSERT_THAT = staticMethod()
        .onClassAny("org.hamcrest.MatcherAssert", "org.junit.Assert")
        .named("assertThat");

    private static final Matcher<ExpressionTree> NULL_VALUE = staticMethod()
        .onClass("org.hamcrest.Matchers")
        .named("nullValue");

    private static final Matcher<ExpressionTree> NULL_VALUE_INVOCATION =
        methodInvocation(NULL_VALUE);

    private static final Matcher<ExpressionTree> ASSSERT_THAT_THING_NULL_VALUE =
        methodInvocation(ASSERT_THAT, MatchType.LAST, NULL_VALUE_INVOCATION);

    @Override
    public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state)
    {
        if (ASSSERT_THAT_THING_NULL_VALUE.matches(tree))
        {
            buildDescription(tree)
                .addFix(SuggestedFixes.somethingGoesHere(...))
                .build();
        }

        return Description.NO_MATCH;
    }
}

我的问题是我无法弄清楚如何从SuggestedFixes. 我想知道这个 API 是否没有很好地充实,或者我是否完全走错了路,应该以更好的方式编写检查?

4

0 回答 0