代码之家  ›  专栏  ›  技术社区  ›  Filipe Freire

引发未选中的异常,而不是不同的预期异常

  •  3
  • Filipe Freire  · 技术社区  · 8 年前

    重构时 Rultor Cactoos 而不是 Guava ,我对的阴性测试有问题 GithubProfileTest GithubProfileValidationTest .

    测试中受影响的重构代码是 GithubProfile.assets 方法和 GithubProfile.asset

    我重构了 assets 方法如下所示:

     public Map<String, InputStream> assets() throws IOException {
        final XML xml = this.read();
        final List<XML> nodes = xml.nodes("/p/entry[@key='assets']/entry");
        return new MapOf<>(
            new Mapped<>(
                nodes,
                input ->
                    new MapEntry<>(
                        input.xpath("@key").get(0),
                        this.asset(input.xpath("text()").get(0))
                    )
            )
        );
    }
    

    在不同的测试用例上 this.asset 呼叫应抛出 Profile.ConfigException Unable to evaluate the expression Method threw 'java.io.UncheckedIOException' exception ,以及 被忽略/隐藏。

    看来 MapOf UncheckedIOException ,因此我无法修复此问题,并且 轮廓配置异常

    不包含任何关于 被抚养。

    2 回复  |  直到 8 年前
        1
  •  3
  •   yegor256    8 年前

    问题是 Iterable#next() (在JDK中)不允许抛出选中的异常(如 Profile.ConfigException ). 这就是为什么 org.cactoos.iterator.Mapped 抓住他们然后扔出去 UncheckedIOException for 回路:

    public Map<String, InputStream> assets() throws IOException {
      final XML xml = this.read();
      final List<XML> nodes = xml.nodes("/p/entry[@key='assets']/entry");
      final List<MapEntry> entries = new LinkedList<>();
      for (final XML node : nodes) {
        entries.add(
          new MapEntry<>(
            input.xpath("@key").get(0),
            this.asset(input.xpath("text()").get(0)) // checked exeption here
          )
        );
      }
      return new MapOf<>(entries);
    }
    
        2
  •  3
  •   aventurin    8 年前

    原因可能是在 org.cactoos.func.UncheckedFunc 迭代以填充地图时。

    由于函数式编程通常不能很好地处理异常,因此API尝试避免声明已检查的异常。所以你可能不得不接受这一点。