View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.checkstyle;
6   
7   import com.qulice.spi.Environment;
8   import com.qulice.spi.Violation;
9   import java.io.File;
10  import java.io.IOException;
11  import java.util.Collection;
12  import org.cactoos.io.ResourceOf;
13  import org.cactoos.text.FormattedText;
14  import org.cactoos.text.IoCheckedText;
15  import org.cactoos.text.TextOf;
16  import org.hamcrest.MatcherAssert;
17  import org.hamcrest.Matchers;
18  import org.junit.jupiter.api.Assertions;
19  import org.junit.jupiter.api.Test;
20  
21  /**
22   * Test case for {@link CheckstyleValidator}'s handling of
23   * {@link FinalSemicolonInTryWithResourcesCheck}.
24   * @since 0.25.1
25   */
26  final class FinalSemicolonInTryWithResourcesCheckTest {
27  
28      @Test
29      void rejectsExtraSemicolonInTryWithResources() throws Exception {
30          final String file = "ExtraSemicolon.java";
31          MatcherAssert.assertThat(
32              "Extra semicolon in try-with-resources head must be reported",
33              this.runValidation(file, false),
34              Matchers.hasItem(
35                  new ViolationMatcher(
36                      "Extra semicolon in the end of try-with-resources head.",
37                      file
38                  )
39              )
40          );
41      }
42  
43      @Test
44      void acceptsTryWithResourcesWithoutSemicolon() throws Exception {
45          Assertions.assertDoesNotThrow(
46              () -> this.runValidation("ValidSemicolon.java", true)
47          );
48      }
49  
50      private Collection<Violation> runValidation(final String file,
51          final boolean passes) throws IOException {
52          final Environment.Mock mock = new Environment.Mock();
53          final Environment env = mock.withParam(
54              "license",
55              String.format(
56                  "file:%s",
57                  new License().savePackageInfo(
58                      new File(mock.basedir(), "src/main/java/foo")
59                  ).withLines("Hello.")
60                      .withEol(String.valueOf('\n')).file()
61              )
62          ).withFile(
63              String.format("src/main/java/foo/%s", file),
64              new IoCheckedText(
65                  new TextOf(
66                      new ResourceOf(
67                          new FormattedText("com/qulice/checkstyle/%s", file)
68                      )
69                  )
70              ).asString()
71          );
72          final Collection<Violation> results =
73              new CheckstyleValidator(env).validate(env.files(file));
74          MatcherAssert.assertThat(
75              "validation result should match expected state",
76              results.isEmpty(),
77              Matchers.is(passes)
78          );
79          return results;
80      }
81  }