View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.pmd;
6   
7   import com.qulice.spi.Environment;
8   import com.qulice.spi.Violation;
9   import java.io.File;
10  import java.util.Collections;
11  import java.util.List;
12  import java.util.stream.Collectors;
13  import org.cactoos.text.TextOf;
14  import org.hamcrest.MatcherAssert;
15  import org.hamcrest.Matchers;
16  import org.junit.jupiter.api.Test;
17  
18  /**
19   * Test case for {@link com.qulice.pmd.rules.CloseInlineResourceRule}.
20   *
21   * @since 0.27.7
22   */
23  final class CloseInlineResourceRuleTest {
24  
25      /**
26       * The name of the rule under test.
27       */
28      private static final String RULE = "CloseInlineResourceRule";
29  
30      @Test
31      void detectsCloseableInsideMethodChain() throws Exception {
32          MatcherAssert.assertThat(
33              "CloseInlineResourceRule should fire on inline closeable expressions",
34              this.violations("InlineCloseableMethodChain.java"),
35              Matchers.hasItem(CloseInlineResourceRuleTest.RULE)
36          );
37      }
38  
39      @Test
40      void detectsArgumentAndChainReceiver() throws Exception {
41          MatcherAssert.assertThat(
42              "CloseInlineResourceRule should catch the argument and chain receiver",
43              Collections.frequency(
44                  this.violations("InlineCloseableMethodChain.java"),
45                  CloseInlineResourceRuleTest.RULE
46              ),
47              Matchers.greaterThanOrEqualTo(2)
48          );
49      }
50  
51      @Test
52      void allowsTryWithResources() throws Exception {
53          MatcherAssert.assertThat(
54              "CloseInlineResourceRule should allow try-with-resources",
55              this.violations("InlineCloseableTryWithResources.java"),
56              Matchers.not(Matchers.hasItem(CloseInlineResourceRuleTest.RULE))
57          );
58      }
59  
60      private List<String> violations(final String file) throws Exception {
61          final String name = String.format("src/main/java/foo/%s", file);
62          final Environment env = new Environment.Mock().withFile(
63              name,
64              new TextOf(this.getClass().getResourceAsStream(file)).asString()
65          );
66          return new PmdValidator(env).validate(
67              Collections.singletonList(new File(env.basedir(), name))
68          ).stream().map(Violation::name).collect(Collectors.toList());
69      }
70  }