2017-09-05 90 views
3

雖然重構Rultor使用Cactoos,而不是Guava,我遇到的GithubProfileTestGithubProfileValidationTest試驗陰性的問題。UncheckedIOException被拋出,而不是不同的預期異常

重構後,正面的測試用例通過了兩個提到的測試類,但是期望特定異常的負面測試用例失敗。 受影響的重構代碼是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,而Profile.ConfigException被忽略/隱藏。

似乎MapOf不知何故未能評估,或「隱藏」,不同之處在於調用this.asset方法提出,提高自身的UncheckedIOException,所以我無法修復它並有Profile.ConfigException提高。

調試時,UncheckedIOException不包含任何提及的Profile.ConfigException信息。

任何提示,爲什麼我可能會得到這種行爲或可能的解決方案?

+0

我看到的唯一一行可以拋出'UncheckedIOException'的代碼就是'read()'方法。它有什麼作用? – fge

回答

3

問題是Iterable#next()(在JDK中)不允許拋出檢查的異常(如Profile.ConfigException)。這就是爲什麼org.cactoos.iterator.Mapped抓住他們並拋出UncheckedIOException。由於JDK設計,這是不可修復的。你可以做的最好的是舊的for loop:

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); 
} 
3

原因可能是在迭代填充地圖時在org.cactoos.func.UncheckedFunc中完成的轉換。

由於功能風格編程通常不能很好地處理異常,因此API會盡量避免聲明檢查的異常。所以你可能不得不忍受這一點。

相關問題