2017-03-16 56 views
1

混合使用有關測試Scalatest 2.2.5,斯卡拉2.11.8,SBT 0.13.13,JDK 1.8.121ScalaTest如何排除MustMatchers如果多個匹配器在

我們的代碼庫的發展和開發者有不同的偏好風格和匹配。在下面的代碼中,測試使用Matchers,它也需要在其聲明中混合一個trait OurCommonTestHelpers,如果它自己在MustMatchers中混合。這很容易解決,只需刪除with Matchers並用must equal替換should equal即可。讓我們假裝我更喜歡動詞should,只是因爲它用於ScalaTest User Guide

我們可能會標準化一天。但是現在,如果發生衝突,是否有可能排除匹配器?

import org.scalatest.{FreeSpec, Matchers} 

class MyBizLogicTest extends FreeSpec 
with Matchers // <-- conflict with MustMatchers from trait OurCommonTestHelpers 
with OurCommonTestHelpers 
{ 
    "A trivial addition" in { 
     (1 + 2) should equal (3) 
    } 
} 

trait OurCommonTestHelpers extends MockitoSugar with MustMatchers { 
    ??? 
} 

代碼失敗編譯:

Error:(26, 7) class MyBizLogicTest inherits conflicting members: 
    method convertSymbolToHavePropertyMatcherGenerator in trait Matchers of type (symbol: Symbol)MyBizLogicTest.this.HavePropertyMatcherGenerator and 
    method convertSymbolToHavePropertyMatcherGenerator in trait MustMatchers of type (symbol: Symbol)MyBizLogicTest.this.HavePropertyMatcherGenerator 
(Note: this can be resolved by declaring an override in class MyBizLogicTest.); 
other members with override errors are: equal, key, value, a, an, theSameInstanceAs, regex, <, >, <=, >=, definedAt, evaluating, produce, oneOf, atLeastOneOf, noneOf, theSameElementsAs, theSameElementsInOrderAs, only, inOrderOnly, allOf, inOrder, atMostOneOf, thrownBy, message, all, atLeast, every, exactly, no, between, atMost, the, convertToRegexWrapper, of 
class MyBizLogicTest extends FreeSpec 

注:我試圖通過import org.scalatest.{MustMatchers => _}排除MustMatchers但這對編譯錯誤沒有影響。

回答

1

我不認爲你可以,因爲這兩類都不會繼承另一類。最明顯的辦法是增加一個額外的類型:

// name just to be clear, I don't suggest actually using this one 
trait OurCommonTestHelpersWithoutMatchers extends ... { 
    // everything in OurCommonTestHelpers which doesn't depend on MustMatchers 
} 

trait OurCommonTestHelpers extends OurCommonTestHelpersWithoutMatchers with MustMatchers { 
    ... 
} 

class MyBizLogicTest extends FreeSpec 
with Matchers 
with OurCommonTestHelpersWithoutMatchers 
{ 
    "A trivial addition" in { 
     (1 + 2) should equal (3) 
    } 
} 

注:我試圖通過進口org.scalatest排除MustMatchers {MustMatchers => _}但這對編譯錯誤沒有影響。 。

無法刪除繼承成員通過不進口他們。如果您通過導入OurCommonTestHelpers來訪問它們,則不會將它們導入MyBizLogicTest(但需要在需要它們的其他類中導入)。