### Question:
PmdSensor implements Sensor { @Override public void execute(SensorContext context) { if (shouldExecuteOnProject()) { for (RuleViolation violation : executor.execute()) { pmdViolationRecorder.saveViolation(violation, context); } } } PmdSensor(RulesProfile profile, PmdExecutor executor, PmdViolationRecorder pmdViolationRecorder, FileSystem fs); @Override String toString(); @Override void describe(SensorDescriptor descriptor); @Override void execute(SensorContext context);  }### Answer:
@Test void should_execute_on_project_without_main_files() { addOneJavaFile(Type.TEST); pmdSensor.execute(sensorContext); verify(executor, atLeastOnce()).execute(); }
@Test void should_execute_on_project_without_test_files() { addOneJavaFile(Type.MAIN); pmdSensor.execute(sensorContext); verify(executor, atLeastOnce()).execute(); }
@Test void should_not_execute_on_project_without_any_files() { pmdSensor.execute(sensorContext); verify(executor, never()).execute(); }
@Test void should_not_execute_on_project_without_active_rules() { addOneJavaFile(Type.MAIN); addOneJavaFile(Type.TEST); when(profile.getActiveRulesByRepository(PmdConstants.REPOSITORY_KEY).isEmpty()).thenReturn(true); when(profile.getActiveRulesByRepository(PmdConstants.TEST_REPOSITORY_KEY).isEmpty()).thenReturn(true); pmdSensor.execute(sensorContext); verify(executor, never()).execute(); }
@Test void should_report_violations() { addOneJavaFile(Type.MAIN); final RuleViolation pmdViolation = violation(); final Report report = report(pmdViolation); when(executor.execute()).thenReturn(report); pmdSensor.execute(sensorContext); verify(pmdViolationRecorder).saveViolation(pmdViolation, sensorContext); }
@Test void should_not_report_zero_violation() { final Report report = report(); when(executor.execute()).thenReturn(report); pmdSensor.execute(sensorContext); verify(pmdViolationRecorder, never()).saveViolation(any(RuleViolation.class), eq(sensorContext)); verifyZeroInteractions(sensorContext); }
@Test void should_not_report_invalid_violation() { final RuleViolation pmdViolation = violation(); final Report report = report(pmdViolation); when(executor.execute()).thenReturn(report); when(report.iterator()).thenReturn(Iterators.forArray(pmdViolation)); pmdSensor.execute(sensorContext); verify(pmdViolationRecorder, never()).saveViolation(any(RuleViolation.class), eq(sensorContext)); verifyZeroInteractions(sensorContext); }
@Test void pmdSensorShouldNotRethrowOtherExceptions() { addOneJavaFile(Type.MAIN); final RuntimeException expectedException = new RuntimeException(); when(executor.execute()).thenThrow(expectedException); final Throwable thrown = catchThrowable(() -> pmdSensor.execute(sensorContext)); assertThat(thrown) .isInstanceOf(RuntimeException.class) .isEqualTo(expectedException); }