ApexRulesDefinition implements RulesDefinition { @VisibleForTesting protected void newRule(Class<?> ruleClass, NewRepository repository) { org.sonar.check.Rule ruleAnnotation = AnnotationUtils.getAnnotation(ruleClass, org.sonar.check.Rule.class); if (ruleAnnotation == null) { throw new IllegalArgumentException( String.format("No Rule annotation was found on %s", ruleClass)); } String ruleKey = ruleAnnotation.key(); if (StringUtils.isEmpty(ruleKey)) { throw new IllegalArgumentException( String.format("No key is defined in Rule annotation of %s", ruleClass)); } NewRule rule = repository.rule(ruleKey); if (rule == null) { throw new IllegalStateException( String.format("No rule was created for %s in %s", ruleClass, repository.key())); } addHtmlDescription(rule, rule.key()); addMetadata(rule, rule.key()); }  @Override void define(Context context);  }
@Test public void testInvalidChecks() throws Exception { RulesDefinition.Context context = new RulesDefinition.Context(); RulesDefinition.NewRepository newRepository = context.createRepository("test", "java"); newRepository.createRule("cardinality"); newRepository.createRule("A1005"); try { rulesDefinition.newRule(CheckWithNoAnnotation.class, newRepository); } catch (IllegalArgumentException illegaArgumentException) { assertThat(illegaArgumentException) .hasMessage(String.format("No Rule annotation was found on class %s", CheckWithNoAnnotation.class.getName())); } try { rulesDefinition.newRule(EmptyRuleKey.class, newRepository); } catch (IllegalArgumentException illegaArgumentException) { assertThat(illegaArgumentException) .hasMessage(String.format("No key is defined in Rule annotation of class %s", EmptyRuleKey.class.getName())); } try { rulesDefinition.newRule(UnregisteredRule.class, newRepository); } catch (IllegalStateException illegalStateException) { assertThat(illegalStateException) .hasMessage(String.format("No rule was created for class %s in test", UnregisteredRule.class.getName())); } rulesDefinition.newRule(CorrectRule.class, newRepository); }